__dict__属性分为类的与类对象的,具体两者的区别如下代码所示
class A(object):
"""
Class A.
"""
a = 0
b = 1
def __init__(self):
self.a = 2
self.b = 3
def test(self):
print('a normal func.')
@staticmethod
def static_test(self):
print('a static func.')
@classmethod
def class_test(self):
print('a calss func.')
obj = A()
print("类的__dict__属性:", A.__dict__)
print("类对象的__dict__属性:", obj.__dict__)
输出结果:
类的__dict__属性: {'__module__': '__main__', '__doc__': '\n Class A.\n ', 'a': 0, 'b': 1, '__init__': <function A.__init__ at 0x108b29a60>, 'test': <function A.test at 0x108cce940>, 'static_test': <staticmethod object at 0x108bbba90>, 'class_test': <classmethod object at 0x108bd51f0>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>}
类对象的__dict__属性: {'a': 2, 'b': 3}
当存在继承关系时,__dict__属性表现如下代码所示
class Parent(object):
a = 0
b = 1
def __init__(self):
self.a = 2
self.b = 3
def p_test(self):
pass
class Child(Parent):
a = 4
b = 5
def __init__(self):
super(Child, self).__init__()
# self.a = 6
# self.b = 7
def c_test(self):
pass
def p_test(self):
pass
p = Parent()
c = Child()
print(Parent.__dict__)
print(Child.__dict__)
print(p.__dict__)
print(c.__dict__)
输出结果:
{'__module__': '__main__', 'a': 0, 'b': 1, '__init__': <function Parent.__init__ at 0x108eb4a60>, 'p_test': <function Parent.p_test at 0x109059940>, '__dict__': <attribute '__dict__' of 'Parent' objects>, '__weakref__': <attribute '__weakref__' of 'Parent' objects>, '__doc__': None}
{'__module__': '__main__', 'a': 4, 'b': 5, '__init__': <function Child.__init__ at 0x1090bd8b0>, 'c_test': <function Child.c_test at 0x1090bd820>, 'p_test': <function Child.p_test at 0x1090bd940>, '__doc__': None}
{'a': 2, 'b': 3}
{'a': 2, 'b': 3}
总结:
- 内置的数据类型没有__dict__属性
- 对于类的__dict__属性来说,就算存着继承关系,父类的__dict__ 并不会影响子类的__dict__
- 对于类对象的__dict__属性来说,父子类对象公用__dict__