class demoClass: instances_created = 0 def __new__(cls,*args,**kwargs): print("__new__():",cls,args,kwargs) instance = super().__new__(cls) instance.number = cls.instances_created cls.instances_created += 1 return instance def __init__(self,attribute): print("__init__():",self,attribute) self.attribute = attribute test1 = demoClass("abc") test2 = demoClass("xyz") print(test1.number,test1.instances_created) print(test2.number,test2.instances_created)输出结果为:
__new__(): <class '__main__.demoClass'> ('abc',) {}
__init__(): <__main__.demoClass object at 0x0000026FC0DF8080> abc
__new__(): <class '__main__.demoClass'> ('xyz',) {}
__init__(): <__main__.demoClass object at 0x0000026FC0DED358> xyz
0 2
1 2
class nonZero(int): def __new__(cls,value): return super().__new__(cls,value) if value != 0 else None def __init__(self,skipped_value): #此例中会跳过此方法 print("__init__()") super().__init__() print(type(nonZero(-12))) print(type(nonZero(0)))运行结果为:
__init__()
<class '__main__.nonZero'>
<class 'NoneType'>
本文链接:http://task.lmcjl.com/news/5682.html