1. __new__方法
__new__ 和 __init__ 共同构成了类的构造方法, __new__返回这个类的实例,并将参数传给init, init初始化这个类
# __new__ 方法实现单例模式
class B(): __instance = None def __new__(cls, *args, **kwargs): # 接收参数并传递给init, if not cls.__instance: cls.__instance = object.__new__(cls) return cls.__instance else: return cls.__instance def __init__(self, a, b): self.a = a self.b = b if __name__ == '__main__': b = B(1, 2) c = B(2, 4) print(id(b)) print(id(c))
2. __del__ 构析方法
当类的生命周期结束的时候调用自动调用该方法
class Foo(): def __init__(self): self.f = open('a.js', 'r') def __del__(self): self.f.close() del self.f print('关闭文件句柄') if __name__ == '__main__': Foo()
3. __setattr__
使用 实例.name = value 给实例属性赋值的时候调用__setattr方法
class Foo(): def __setattr__(self, key, value): print('设置值{} : {}'.format(key, value)) self.__dict__[key] = value if __name__ == '__main__': a = Foo() a.name = 'zj'
4. __iter__ 和 __next__ 方法
__iter__ 将对象变成一个迭代器
__next__ for循环取值的时候触发
class Foo(): def __init__(self, start, end): self.start = start self.end = end def __iter__(self): return self def __next__(self): if self.start >= self.end: raise StopIteration n = self.start self.start += 1 return n for i in Foo(1,3): print(i)
5. 上下文管理
with 一个对象的时候执行对象的__enter__ 方法
with 结束的时候执行对象的 __exist__ 方法
class Foo(): def __init__(self, file): self.file = file def __enter__(self): print('打开文件') self.f = open(self.file) return self.f def __exit__(self, exc_type, exc_val, exc_tb): print('关闭文件') self.f.close() with Foo('a.js') as f: print(f.read())