Python - 面向对象编程 - __dict__

本文探讨了Python类的内部结构,指出类和实例的属性、方法都以字典形式存储。通过__dict__属性,我们可以查看类或实例包含的属性和方法。实例调用__dict__显示实例属性,类调用则显示类属性和方法。在多继承场景下,每个类都有自己的__dict__,不包含父类的。此外,通过修改实例的__dict__可以直接改变属性值。
摘要由CSDN通过智能技术生成

为什么要讲 __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': '新的小菠萝'}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小菠萝测试笔记

来支持下测试小锅锅

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值