Why?
你應該閱讀異常消息:「AttributeError的:SubPerson實例沒有屬性'name'
」,這清楚地表明,你已經在使用的主要表達p = SubPerson()
創建SubPerson
的實例p
沒有屬性'name'
- 這就是爲什麼它會拋出AttributeError
異常。
讓我們試着主動解釋你的代碼,看看:
>>> class Person:
... def setname(self, name):
... self.name = name
... def display(self):
... print(self.name)
...
>>> class SubPerson(Person):
... def display(self):
... print("Name: {0}".format(self.name))
...
>>> p = SubPerson()
>>> p.name # Notice
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SubPerson instance has no attribute 'name'
>>>
通知行p.name
- 你得到相同的異常!事實上p
有名稱的屬性'name'
可以用內省技術使用__dict__
和繼承使用dir()
功能屬性的p
所有屬性列表,請參閱下面
>>> p.__dict__
{} # p don't have it any it own attribute
>>> dir(p) # either don't inerited attribute 'name'
['__doc__', '__module__', 'display', 'setname']
>>>
通知只是屬性,從Person類p
繼承是「顯示器','setname'但不是name
。
How can I fix this?
你有一些技巧來糾正如下代碼:
Python是動態語言,你可以明確地在對象名稱空間添加新的名稱:
>>> p.name = "grijesh"
>>> p.__dict__ # Now `p` has 'name' attributes
{'name': 'grijesh'}
>>> p.display() # it is safe to call display
Name: grijesh
使用您的setname
作爲@Tasawer Nawaz的回答建議。
使用__init__
函數和實現對象的構造函數作爲@ T.C.的答案給出。
基本上在所有技術要連接'name'
屬性在display()
函數法訪問它之前SubPerson實例對象。
你永遠不會調用'setname',父母和孩子都不會有'__init__' - 你期望發生什麼? – jonrsharpe 2014-09-11 12:20:03
即使你使'p'成爲Person,它也不起作用:它與子類化無關。 – 2014-09-11 12:34:23
我是否正確回答了您的問題? – Oni1 2014-09-11 13:18:09