1
我想了解蟒蛇的一羣模式,我認爲可以通過以下方式來表達:瞭解束模式和自.__ dict__
class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)
用法:
bunch = Bunch(name='Loving the bunch class')
print(bunch.name)
我瞭解一個字典做什麼更新時間:
dict1.update(dict2)
將增加dict2的內容(名稱:值對)dict1。這裏是我的問題:
什麼是「__dict__」?爲什麼它不顯示在對象的目錄中,而在hasattr()中顯示?例如:
>>> class test:
def __init__(self, a):
self.a = a
>>> t = test(10)
>>> t.__dict__
{'a': 10}
>>> hasattr(t, "a")
True
>>> hasattr(t, "__dict__")
True
>>> dir(t)
['__doc__', '__init__', '__module__', 'a']
>>>
最後,我怎麼能在一堆類與點運算符訪問屬性「名稱」?
bunch = Bunch(name='Loving the bunch class')
print(bunch.name)
這不是SO結構問多個問題,它可能是最好的,你單獨問你的問題。這就是說,你的問題是那些在嘗試使用它之前閱讀文檔和學習Python最容易回答的問題。爲什麼對象像他們一樣行事,或者類成員是如何工作的都包含在文檔中。 http://docs.python.org/2/tutorial/classes.html – 2013-04-28 12:16:21
可能的重複[在Python中dir和\ _ \ _ dict \ _ \ _最大的區別是什麼](http://stackoverflow.com/questions/14361256/whats-the-the-difference-between-dir-and-dict-in-python) – Aya 2013-04-28 12:28:19
相關:http://stackoverflow.com/questions/6761106/inspect-getmembers-vs-dict-items-vs- DIR – Aya 2013-04-28 12:28:47