運行錯誤,求指教
class Program():
??? def __new__(cls,*args,**kwargs):
??????? print "call_new_method"
??????? print args
??????? return super(Program.cls).__new__(cls,*args,**kwargs)
??? def __init__(self,name,age):
??????? print "call_init_method"
??????? self.name=name
??????? self.age=age
??? def __eq__(self,other):
??????? if isinstance(other,Program):
??????????? if self.age==other.age:
??????????????? return True
??????????? else:
??????????????? return False
??????? else:
??????????? raise Exception("The type of object must be Program")
??? def __add__(self,other):
??????? if isinstance(other,Program):
??????????? return self.age+other.age
??????? else:
??????????? raise Exception("The type of object must be Program")
? ?
p1=Program("Thom",63)
p2=Program("Tom",60)
print p1==p2
print p1+p2
代碼運行結(jié)果為:call_init_method
call_init_method
False
123
為什么覺得__new__方法沒有執(zhí)行 ?
后添加繼承object,運行結(jié)果為?
call_new_method
('Thom', 63)
Traceback (most recent call last):
? File "D:\Java\myeclipse\workspace\IPython\com\Test\test_operation.py", line 24, in <module>
??? p1=Program("Thom",63)
? File "D:\Java\myeclipse\workspace\IPython\com\Test\test_operation.py", line 5, in __new__
??? return super(Program.cls).__new__(cls,*args,**kwargs)
AttributeError: type object 'Program' has no attribute 'cls'
并請問cls,self區(qū)別
2016-11-26
? ? def __new__(cls,*args,**kwargs):
??????? print "call_new_method"
??????? print args
??????? return super(Program.cls).__new__(cls,*args,**kwargs)
最后一句行該是return super(Program,cls).__new__(cls,*args,**kwargs)
super(Program, cls)方法里參數(shù)用逗號分隔。
(盯著屏幕看了半天。。。。。。