理解群体模式和自我__

2024-06-06 08:54:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解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)

Tags: thenameselfinitdefupdatedictclass