為什么要講 __dict__
- 在 Python 類的內部,無論是類屬性、實例屬性、實例方法、類方法、靜態方法,都是以字典的形式進行存儲的,其中屬性名作為鍵,而值作為該鍵對應的值
- 為了方便查看類包含了哪些屬性、方法,就可以使用類提供的 __dict__ 屬性,記住是一個屬性,不是方法來的
單繼承的栗子
class PoloBlog: sum = 0 def __init__(self, name): self.name = name def test(self): pass @classmethod def test_cls(cls): pass @staticmethod def test_static(): pass blog = PoloBlog("小菠蘿") blog.test() # 實例對象調用 print(blog.__dict__) # 類對象調用 print(PoloBlog.__dict__) # 輸出結果 {'name': '小菠蘿'} {'__module__': '__main__', 'sum': 0, '__init__': <function PoloBlog.__init__ at 0x105d2b0d0>, 'test': <function PoloBlog.test at 0x105d4d310>, 'test_cls': <classmethod object at 0x105c47fa0>, 'test_static': <staticmethod object at 0x105c47d90>, '__dict__': <attribute '__dict__' of 'PoloBlog' objects>, '__weakref__': <attribute '__weakref__' of 'PoloBlog' objects>, '__doc__': None}
- 如果用實例對象調用 __dict__ 會輸出所有實例屬性組成的字典
- 用類對象調用 __dict__ 會輸出所有實例方法、類屬性、類方法組成的字典
多繼承的栗子
class A: a = 0 def __init__(self): self.name = "小菠蘿" pass def test(self): pass class B(A): b = 0 def __init__(self): super(B, self).__init__() self.age = 24 # 通過類對象調用 print(A.__dict__) print(B.__dict__) # 通過實例對象調用 a = A() b = B() print(a.__dict__) print(b.__dict__) # 輸出結果 {'__module__': '__main__', 'a': 0, '__init__': <function A.__init__ at 0x1022553a0>, 'test': <function A.test at 0x102255430>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None} {'__module__': '__main__', 'b': 0, '__init__': <function B.__init__ at 0x1022554c0>, '__doc__': None} {'name': '小菠蘿'} {'name': '小菠蘿', 'age': 24}
父類有自己的 __dict__,同樣子類也有自己的 __dict__,它不會包含父類的 __dict__
通過 __dict__ 修改值
還是上面的代碼
a = A() print(a.__dict__) # 修改屬性值 a.__dict__["name"] = "新的小菠蘿" print(a.__dict__) # 輸出結果 {'name': '小菠蘿'} {'name': '新的小菠蘿'}