Python属性 __dict__

1. _ dict _属性

# -*- coding: utf-8 -*-

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()
# 类.__dict__
print(A.__dict__)
# 类对象.__dict__
print(obj.__dict__)

# 类的静态函数、类函数、普通函数、if 全局变量以及一些内置的属性都是放在类__dict__里的:
# 对象的__dict__中存储了一些self.xxx的一些东西

结果

{'__module__': '__main__', '__doc__': '\n    Class A.\n    ', 'a': 0, 'b': 1, '__init__': <function A.__init__ at 0x000001DDCB352288>, 'test': <function A.test at 0x000001DDCB352F78>, 'static_test': <staticmethod object at 0x000001DDCB3AFB48>, 'class_test': <classmethod object at 0x000001DDCB3AFB88>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>}
{'a': 2, 'b': 3}

2. 内置的数据类型是没有_ dict _属性

int, list, dict等这些常用的数据类型是没有__dict__属性的

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

结果:

  1. 每个类有自己的__dict__属性,就算存着继承关系,父类的__dict__ 并不会影响子类的__dict__
  2. 对象也有自己的__dict__属性, 存储self.xxx 信息,父子类对象公用__dict__
{'__module__': '__main__', 'a': 0, 'b': 1, '__init__': <function Parent.__init__ at 0x000001C4E30C2EE8>, 'p_test': <function Parent.p_test at 0x000001C4E30C2E58>, '__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 0x000001C4E30C2DC8>, 'c_test': <function Child.c_test at 0x000001C4E30C2D38>, 'p_test': <function Child.p_test at 0x000001C4E30C2CA8>, '__doc__': None}
{'a': 2, 'b': 3}
{'a': 2, 'b': 3}

_ dict _

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值