class Person(object):
def __call__(self, *args, **kwargs): # 对象加括号或对象.__call__()方法时调用,可以传参数
print("__call__方法被调用")
def __init__(self): # 类实例化时创建对象时调用
print("__init__方法被调用")
def __new__(cls, *args, **kwargs): # 通过类创建对象的时候调用__new__方法
print("__new__方法被调用")
return super(Person, cls).__new__(cls, *args, **kwargs)
def __str__(self): # 对象使用str()方法时调用
return "__str__方法被调用"
def __enter__(self): # 对象使用with的时候调用(在未进入with之前调用)
print("__enter__方法被调用")
def __exit__(self, exc_type, exc_val, exc_tb): # 对象使用with的时候调用(在完成with之后调用)
print("__exit__方法被调用")
def __len__(self): # 对象使用len()方法时调用
return 4
person = Person()
person()
print(str(person))
with person:
print("with")
print(len(person))
上面代码的输出
__new__方法一般用于创建单例模式(无论创建多少个对象,都是同一个)
class Animal(object):
instance = None
def __new__(cls, *args, **kwargs):
if cls.instance is None:
cls.instance = super(Animal, cls).__new__(cls, *args, **kwargs)
return cls.instance
dog = Animal()
cat = Animal()
print(id(dog))
print(id(cat))
print(dog is cat)
print(dog == cat)
输出:
可以看到dog和cat对象的内存地址是一样的,指向同一个