Skip to main content
 首页 » 编程设计

python之理解束模式和 self.__dict__

2025年05月04日16xing901022

我试图理解 python 中的束模式,我相信可以用以下方式表达:

class Bunch: 
    def __init__(self, **kwds): 
        self.__dict__.update(kwds) 

用法:

bunch = Bunch(name='Loving the bunch class') 
print(bunch.name) 

我明白 update 对 dict 做了什么:

dict1.update(dict2) 

将 dict2(name:value pairs) 的内容添加到 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 = Bunch(name='Loving the bunch class') 
print(bunch.name) 

请您参考如下方法:

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

来自 Data Model (Python Docs)