我正在尝试理解python中的bunch模式,我相信它可以用以下方式表达:
class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)用法:
bunch = Bunch(name='Loving the bunch class')
print(bunch.name)我知道update在字典上做了什么:
dict1.update(dict2)将在dict1中添加dict2(名称:值对)的内容。下面是我的问题:
什么是"__dict__"?为什么它没有显示在对象的dir中,而显示在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类中的属性'name‘?
bunch = Bunch(name='Loving the bunch class')
print(bunch.name)发布于 2013-04-28 20:20:13
类具有由字典对象实现的命名空间。在此字典中,类属性引用被转换为查找,例如,C.x被转换为C.__dict__["x"]
来自Data Model (Python Docs)
https://stackoverflow.com/questions/16262670
复制相似问题