-
_len_
class A: def __init__(self): self.a = 1 self.b = 2 def __len__(self): return len(self.__dict__) a = A() print(len(a)) # len 一个对象就会触发 __len__方法。
-
_hash_
class A: def __init__(self): self.a = 1 self.b = 2 def __len__(self): return hash(str(self.a)+str(self.b)) a = A() print(hash(a)) # 获取哈希值
-
__str__ (优先级高于__repr__) ***
class A: def __init__(self,name,age): self.name = name self.age = age def __str__(self): return f'姓名:{self.name} 年龄:{self.age}' a = A('海狗',18) print(a) # 打印对象触发__str__方法
-
_repr_
用法和__str__类似,返回值是什么样就返回什么样(原形毕露)
-
_eq_
class A: def __init__(self): self.a = 1 self.b = 2 def __eq__(self, other): if self.a == other.a and self.b == other.b: return True obj1 = A() obj2 = A() print(obj1 == obj2)
-
_call_ ***
class A: def __init__(self): pass def __call__(self, *args, **kwargs): print('我好帅') obj = A() obj() # 对象() 自动触发对象从属于类(父类)的__call__方法
-
_del_
析构方法,当对象在内存中被释放时,自动触发执行。
-
_new_ ***
对象是object类的__new__方法 产生了一个对象.
实例化对象时 先触发 object 的__new__方法,此方法在内存中开辟一个对象空间.再执行__init__方法,给对象封装属性.
单例模式: (节约系统资源)
class A: __instance = None def __init__(self,name): self.name = name def __new__(cls, *args, **kwargs): if not cls.__instance: cls.__instance = object.__new__(cls) return cls.__instance obj = A('liky')
-
__item__系列
class A: def __init__(self,name): self.name = name def __getitem__(self, item): print(item) print(self.__dict__[item]) def __setitem__(self, key, value): print(key) print(value) self.__dict__[key] = value def __delitem__(self, key): print(key) obj = A('海狗') obj['name'] # 执行getitem obj['age'] = 18 # 执行setitme del obj['age'] # 执行delitme
-
_delattr_
class A: def __init__(self,name): self.name = name def __delattr__(self, item): print(item) obj = A('海狗') del obj.name
-
__enter__ _exit_ 上下文管理
class A: def __init__(self,name): self.name = name def __enter__(self): print(111) return self # 必须返回self def __exit__(self, exc_type, exc_val, exc_tb): print(333) with A('海狗') as obj: print(obj.name) # 111 # 海狗 # 333 # __enter__和__exit__两个方法是一组,一起出现
-
_iter_
class A: def __init__(self,name): self.name = name def __iter__(self): for i in range(10): yield i obj = A('海狗') for i in obj: print(i)