2014-01-20 71 views
3

當我嘗試動態添加屬性到對象類的實例時,我得到一個AttributeError。但是,可以用對象的子類實例來完成它。 有人知道爲什麼嗎?關於在Python 2.x中動態分配屬性

>>> obj = object() 
>>> obj.new_attr = "some value" 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
AttributeError: 'object' object has no attribute 'new_attr' 
>>> class MyClass(object): 
...  pass 
... 
>>> obj = MyClass() 
>>> obj.new_attr = "some value" 
>>> print obj.new_attr 
some value 

回答

5

有關於該文檔中的說明:

http://docs.python.org/3/library/functions.html#object

注意object沒有__dict__,所以你不能指定任意屬性的一個實例對象類「。

還有關於這條巨蟒的郵件列表上的討論:

https://mail.python.org/pipermail/python-list/2011-October/614249.html

+0

如何'object'沒有'__dict__',但其所有子類中有一個隱含?這種打破繼承。 – ApproachingDarknessFish

+0

@ValekHalfHeart在我的編輯鏈接應該清除你的疑惑 – pkacprzak

+0

謝謝。很好的答案! – matiascelasco