1、构造方法
实例化过程:构造->初始化
构成方法必须要有返回值,返回给初始化方法的self
class A: def __init__(self): self.x = 1 print('init') def __new__(cls, *args, **kwargs): print('new') return object.__new__(cls) a = A()
2、单例模式
关键:构造方法,返回相同的实例对象
class Singleton: def __new__(cls, *args, **kwargs): if not hasattr(cls, "instance"): cls.instance = object.__new__(cls) return cls.instance a = Singleton() b = Singleton()