【发布时间】:2013-04-28 12:05:48
【问题描述】:
我正在尝试理解python中的束模式,我相信可以用以下方式表达:
class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)
用法:
bunch = Bunch(name='Loving the bunch class')
print(bunch.name)
我了解更新对字典的作用:
dict1.update(dict2)
将 dict2(name:value 对) 的内容添加到 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 最容易回答的问题。文档中涵盖了对象为何如此行事,或类成员如何工作。 docs.python.org/2/tutorial/classes.html
标签: python