python之类里面的__dict__属性详解
前言
python是面向对象的,对象有属性和方法,可以通过__dict__查看对象的属性。
我们都知道Python一切皆对象,那么Python究竟是怎么管理对象的呢?
__dict__查看对象属性
首先弄清楚2个概念,类(A)和类的实例对象(A()), 如下代码:
- count 是A的类属性
- name和age是 A类的实例对象A()属性
- start 是实例方法,默认带self参数
- stop 是静态方法,可以不带默认参数
- open 是类方法,默认带cls参数
class A(object): count = 0 def __init__(self): self.name = "yoyo" self.age = 18 def start(self): """实例方法""" print("start-11111") @staticmethod def stop(): """静态方法""" print("stop-22222") @classmethod def open(cls): print("open-3333333")
A类有属性和方法,抽象的来讲,方法也可以看成类的属性(方法属性)
print(A.__dict__) # A类属性 a = A() # a是A类的实例对象 print(a.__dict__) # A类的实例对象属性
运行结果:
{'__module__': '__main__', 'count': 0, '__init__': <function A.__init__ at 0x000001F84781AAE8>, 'start': <function A.start at 0x000001F84781AB70>, 'stop': <staticmethod object at 0x000001F84783A2B0>, 'open': <classmethod object at 0x000001F84783A2E8>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None} {'name': 'yoyo', 'age': 18}
从运行结果可以看出,A的类属性有count,还有定义的一些方法(__init__构造方法,还有实例方法,静态方法,类方法)。
A()实例对象只有__init__构造方法里面的name和age属性(count是类属性,并不是类的实例对象属性)。
如果我们直接A.name 和 A.age就会报错:
print(A.name) print(A.age)
报错
Traceback (most recent call last): File "D:/wangyiyun_hrun3/demo/a.py", line 27, in <module> print(A.name) AttributeError: type object 'A' has no attribute 'name'
因为name和age属性在__init__构造方法里面,只有当A类实例化的时候,才会执行__init__构造方法,这时候才会有name和age属性了。
继承时__dict__属性
当B类继承A类的时候,A类和B类都有自己的类属性 count,也各自有自己的__init__构造方法:
class A(object): count = 0 def __init__(self): self.name = "yoyo" self.age = 18 def start(self): """实例方法""" print("start-11111") @staticmethod def stop(): """静态方法""" print("stop-22222") @classmethod def open(cls): print("open-3333333") class B(A): count = 22 def __init__(self): super().__init__() self.name = "hello" self.age = 22 def new(self): print("new--44444") print(A.__dict__) print(B.__dict__) a = A() b = B() print(a.__dict__) print(b.__dict__)
运行结果:
{'__module__': '__main__', 'count': 0, '__init__': <function A.__init__ at 0x000001FD03F8AAE8>, 'start': <function A.start at 0x000001FD03F8AB70>, 'stop': <staticmethod object at 0x000001FD03FAA470>, 'open': <classmethod object at 0x000001FD03FAA4A8>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None} {'__module__': '__main__', 'count': 22, '__init__': <function B.__init__ at 0x000001FD03F8AD08>, 'new': <function B.new at 0x000001FD03F8AD90>, '__doc__': None} {'name': 'yoyo', 'age': 18} {'name': 'hello', 'age': 22}
从运行结果可以看出
- A类和B类的类属性count是不一样的,
- 虽然B类继承了A类,方法属性也不一样,可以清楚的区分出哪些是A类的方法属性,哪些是B类的方法属性
并不是所有的对象都存在__dict__属性
虽然说一切皆对象,但对象也有不同,一些内置的数据类型是没有__dict__属性的,如下:
num = 3 ll = [] dd = {} print num.__dict__ print ll.__dict__ print dd.__dict__
运行结果:
Traceback (most recent call last): File "f:\python\test.py", line 54, in <module> print num.__dict__ AttributeError: 'int' object has no attribute '__dict__' Traceback (most recent call last): File "f:\python\test.py", line 55, in <module> print ll.__dict__ AttributeError: 'list' object has no attribute '__dict__' Traceback (most recent call last): File "f:\python\test.py", line 56, in <module> print dd.__dict__ AttributeError: 'dict' object has no attribute '__dict__'
去期待陌生,去拥抱惊喜。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!