【问题标题】:Understanding the Bunch Pattern and self.__dict__理解 Bunch 模式和 self.__dict__
【发布时间】: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)

【问题讨论】:

标签: python


【解决方案1】:

一个类有一个由字典对象实现的命名空间。类属性引用被翻译成这个字典中的查找,例如,C.x 被翻译成C.__dict__["x"]

来自Data Model (Python Docs)

【讨论】:

    猜你喜欢
    • 2014-04-05
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多