python单例模式-特殊方法
一、单例模式
由于类的每一次实例都是不同的对象,在开发中可能需要每一次实例都必须是同一个对象,比如读取配置文件。这种模模式成为单例模式
实现流程
class Cls:
i = None
def __new__(cls, *args, **kwargs):
if cls.i == 0:
cls.i = super(Cls, cls).__new__(cls)
return cls.i
cl1 = Cls()
cl2 = Cls()
print(id(cl1), id(cl2)) # 1698079553136 1698079553136 同一个对象
__new__方法: 创建并返回一个实例的引用
补充
super(ClassName, self/cls): 调用上一级类的方法
- ClassName: 按继承顺序, 被调用方法类的下一级类名.
- self/cls: 当前使用这个方法的实例或这时类
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
class A:
def search(self):
print("A类")
class B:
def search(self):
print("B类")
class C(A):
def search(self):
print("C类继承A类")
class D(B):
def search(self):
print("D类继承B类")
class E(C, D):
def search(self):
super(C, self).search() # 调用A类的方法
print(E.mro())
e = E()
e.search()
二、特殊方法
一个类可以通过定义具有特殊名称的方法来实现由特殊语法所引发的特定操作
1 基本方法
__new__(cls[, ...]): 调用以创建一个cls类的新实例, 并返回实例的引用给self(新建实例时触发)__init__(self[, ...]): 构造器,当一个实例被创建的时候调用的初始化方法(实例化时触发)__del__(self): 析构器,当一个实例被销毁的时候调用的方法(销毁实例时触发)__call__(self[, args...]): 允许一个类的实例像函数一样被调用(类被当成函数调用时触发)__repr__(self): 当被 repr() 调用时的行为; 此方法通常被用于调试,因此确保其表示的内容包含丰富信息且无歧义是很重要的。__str__(self): 通过str(object)以及内置函数format()和print()调用以生成一个对象的“非正式”或格式良好的字符串表示__bytes__(self): 当被 bytes() 调用时的行为, 生成一个对象的字节串表示。这应该返回一个 bytes 对象__hash__(self): 当被 hash() 调用时的行为__bool__(self): 当被 bool() 调用时的行为,应该返回 True 或 False__format__(self, format_spec): 当被 format() 调用时的行为
2 属性相关
__getattr__(self, name): 当用户试图获取一个不存在的属性时的行为(访问属性失败后触发)__getattribute__(self, name): 当该类的属性被访问时的行为(getattr()和obj.name触发此方法)__setattr__(self, name, value): 当一个属性被设置时的行为(setattr()和obj.name = value触发此方法)__delattr__(self, name): 当一个属性被删除时的行为(delattr()和del obj.name触发此方法)__dir__(self): 当 dir() 被调用时的行为__get__(self, instance, owner): 当描述符的值被取得时的行为__set__(self, instance, value): 当描述符的值被改变时的行为__delete__(self, instance): 当描述符的值被删除时的行为
3 比较运算符行为
__lt__(self, other): 定义小于号的行为:x < y调用x.__lt__(y)__le__(self, other): 定义小于等于号的行为:x <= y调用x.__le__(y)__eq__(self, other): 定义等于号的行为:x == y调用x.__eq__(y)__ne__(self, other): 定义不等号的行为:x != y调用x.__ne__(y)__gt__(self, other): 定义大于号的行为:x > y调用x.__gt__(y)__ge__(self, other): 定义大于等于号的行为:x >= y调用x.__ge__(y)
4 算术运算符行为
__add__(self, other): 加法的行为:+__sub__(self, other): 减法的行为:-__mul__(self, other): 乘法的行为:*__truediv__(self, other): 真除法的行为:/__floordiv__(self, other): 整数除法的行为://__mod__(self, other): 取模算法的行为:%__divmod__(self, other): 当被divmod()调用时的行为__pow__(self, other[, modulo]): 当被power()调用或**运算时的行为__lshift__(self, other): 按位左移位的行为:<<__rshift__(self, other): 按位右移位的行为:>>__and__(self, other): 按位与操作的行为:&__xor__(self, other): 定义按位异或操作的行为:^__or__(self, other): 定义按位或操作的行为:|
5 反运算符行为
__radd__(self, other): 与__add__相同,当左操作数不支持(+)时被调用__rsub__(self, other): 与__sub__相同, 当左操作数不支持(-)时被调用__rmul__(self, other): 与__mul__相同, 当左操作数不支持(*)时被调用__rtruediv__(self, other): 与__truediv__相同, 当左操作数不支持(/)时被调用__rfloordiv__(self, other): 与__floordiv__相同,当左操作数不支持(//)时被调用__rmod__(self, other): 与__mod__相同,当左操作数不支持(%)时被调用__rdivmod__(self, other): 与__divmod__相同,当左操作数不支持(divmod())时被调用__rpow__(self, other): 与__pow__相同,当左操作数不支持(**)时被调用__rlshift__(self, other): 与__lshift__相同,当左操作数不支持(<<)时被调用__rrshift__(self, other): 与__rshift__相同,当左操作数不支持(>>)时被调用__rand__(self, other): 与__and__相同,当左操作数不支持(&)时被调用__rxor__(self, other): 与__xor__相同,当左操作数不支持(^)时被调用__ror__(self, other): 与__or__相同,当左操作数不支持(|)时被调用
6 增强赋值运算符行为
__iadd__(self, other): 赋值加法的行为:+=__isub__(self, other): 赋值减法的行为:-=__imul__(self, other): 赋值乘法的行为:*=__itruediv__(self, other): 赋值真除法的行为:/__ifloordiv__(self, other): 赋值整数除法的行为://__imod__(self, other): 赋值取模算法的行为:%__ipow__(self, other[, modulo]):**=运算时的行为__ilshift__(self, other): 赋值按位左移位的行为:<<=__irshift__(self, other): 赋值按位右移位的行为:>>=__iand__(self, other): 赋值按位与操作的行为:&=__ixor__(self, other): 赋值定义按位异或操作的行为:^=__ior__(self, other): 赋值定义按位或操作的行为:|=
7 一元运算符行为
__pos__(self): 正号的行为:+x__neg__(self): 负号的行为:-x__abs__(self): 当被abs()调用时的行为__invert__(self): 按位求反的行为:~x
8 类型转换行为
-
__complex__(self): 当被 complex() 调用时的行为(需要返回恰当的值) -
__int__(self): 当被 int() 调用时的行为(需要返回恰当的值) -
__float__(self): 当被 float() 调用时的行为(需要返回恰当的值) -
__round__(self[, n]): 当被 round() 调用时的行为(需要返回恰当的值) -
__index__(self):- 当对象是被应用在切片表达式中时,实现整形强制转换
- 如果你定义了一个可能在切片时用到的定制的数值型,你应该定义 index
- 如果 index 被定义,则 int 也需要被定义,且返回相同的值
-
__enter__(self):- 定义当使用
with语句时的初始化行为 __enter__的返回值被with语句的目标或者as后的名字绑定
- 定义当使用
-
__exit__(self, exc_type, exc_value, traceback):- 定义当一个代码块被执行或者终止后上下文管理器应该做什么
- 一般被用来处理异常,清除工作或者做一些代码块执行完毕之后的日常工作
9 容器类型行为
__len__(self): 当被 len() 调用时的行为(返回容器中元素的个数)__getitem__(self, key): 获取容器中指定元素的行为,相当于 self[key]__setitem__(self, key, value): 设置容器中指定元素的行为,相当于 self[key] = value__delitem__(self, key): 删除容器中指定元素的行为,相当于 del self[key]__iter__(self): 当迭代容器中的元素的行为__reversed__(self): 当被 reversed() 调用时的行为__contains__(self, item): 当使用成员测试运算符(in 或 not in)时的行为
本文来自博客园,作者:I'm_江河湖海,转载请注明原文链接:https://www.cnblogs.com/jhhh/p/16761544.html

浙公网安备 33010602011771号