1
我測試蟒蛇的傳承,我有這樣的:爲什麼我的python子類不能識別超類的屬性?
__metaclass__=type
class b:
def __init__(s):
s.hungry=True
def eat(s):
if(s.hungry):
print "I'm hungry"
else:
print "I'm not hungry"
class d(b):
def __init__(s):
super(b,s).__init__()
def __mysec__(s):
print "secret!"
obj=d()
obj.eat()
有運行時錯誤爲:
Traceback (most recent call last):
File "2.py", line 17, in ?
obj.eat()
File "2.py", line 6, in eat
if(s.hungry):
AttributeError: 'd' object has no attribute 'hungry'
我不明白這一點,因爲超類的「B」有s.hungry在其init,並且子類在其自己的「init」 內部調用「超級」爲什麼仍然,python說「d」對象沒有屬性「飢餓」?
另一個困惑:錯誤消息將「d」視爲對象,但我將其定義爲一個類! 我弄錯了什麼,如何使它工作?
使用'super'當前類,而不是父類。即'super(d,s).__ init __()' – mVChr
另外,我強烈建議不要在Python中使用單字母名稱。我建議通過https://www.python.org/dev/peps/pep-0008/ – mVChr
閱讀python3中的super()非常簡單,你不需要傳遞參數。 –