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

输出结果:

类的__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}

总结:

  1. 内置的数据类型没有__dict__属性
  2. 对于类的__dict__属性来说,就算存着继承关系,父类的__dict__ 并不会影响子类的__dict__
  3. 对于类对象的__dict__属性来说,父子类对象公用__dict__
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值