Python中__dict__属性介绍

__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__)

输出结果:

[En]

Output result:

&#x7C7B;&#x7684;__dict__&#x5C5E;&#x6027;&#xFF1A; {'__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>}
&#x7C7B;&#x5BF9;&#x8C61;&#x7684;__dict__&#x5C5E;&#x6027;&#xFF1A; {'a': 2, 'b': 3}
</attribute></attribute></classmethod></staticmethod></function></function>

当存在继承关系时,__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__)

输出结果:

[En]

Output result:

{'__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}
</function></function></function></attribute></attribute></function></function>

总结:

  1. 内置的数据类型没有__dict__属性
  2. 对于类的__dict__属性来说,就算存着继承关系,父类的__dict__ 并不会影响子类的__dict__
  3. 对于类对象的__dict__属性来说,父子类对象公用__dict__

Original: https://blog.csdn.net/sinat_34241861/article/details/121456827
Author: 小小平不平凡
Title: Python中__dict__属性介绍

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/6423/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

免费咨询
免费咨询
扫码关注
扫码关注
联系站长

站长Johngo!

大数据和算法重度研究者!

持续产出大数据、算法、LeetCode干货,以及业界好资源!

2022012703491714

微信来撩,免费咨询:xiaozhu_tec

分享本页
返回顶部