亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

運行錯誤,求指教

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

代碼運行結果為:call_init_method
call_init_method
False
123

為什么覺得__new__方法沒有執行 ?

后添加繼承object,運行結果為?

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區別

正在回答

1 回答

? ? 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)方法里參數用逗號分隔。

(盯著屏幕看了半天。。。。。。


2 回復 有任何疑惑可以回復我~
#1

JoshuaShang 提問者

天,居然標點打錯了,感謝
2016-11-29 回復 有任何疑惑可以回復我~
#2

晚唱 回復 JoshuaShang 提問者

嘿嘿,不謝,一起加油。
2016-11-29 回復 有任何疑惑可以回復我~

舉報

0/150
提交
取消

運行錯誤,求指教

我要回答 關注問題
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號