我试图理解python中的bunch模式,我相信可以用以下方式表示:
class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)
用法:
bunch = Bunch(name='Loving the bunch class')
print(bunch.name)
我知道一个dict的更新是什么:
dict1.update(dict2)
将dict2的内容(名称:值对)添加到dict1。我的问题来了:
什么是“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)
类具有由字典对象实现的命名空间。类属性引用被转换为此字典中的查找,例如,
C.x
被转换为C.__dict__["x"]
来自Data Model (Python Docs)
相关问题 更多 >
编程相关推荐