相关文章推荐
Python类和对象
9 类特殊成员(属性和方法)
9.1 Python __new__
9.2 Python __repr__
9.3 Python __del__()
9.4 Python __dir__()
9.5 Python __dict__
9.6 Python setattr、getattr、hasattr
9.7 Python issubclass和isinstance
9.8 Python __call__()
9.9 什么是运算符重载,Python可重载运算符有哪些?
9.10 Python重载运算符实现自定义序列
9.11 Python迭代器
9.12 【Python项目实战】迭代器实现字符串的逆序输出
9.13 Python生成器
9.14 Python更高级的生成器用法!
9.15 Python @函数装饰器
9.16 结合实例,深入了解装饰器!
Python异常处理机制 Python模块和包 Python文件操作(I/O)
Python 类的内部,无论是类属性还是实例属性,都是以字典的形式进行存储的,其中属性名作为键,而值作为该键对应的值。
为了方便用户查看类中包含哪些属性,Python 类提供了 __dict__ 属性 。需要注意的一点是,该属性可以用类名或者类的实例对象来调用,用类名直接调用 __dict__,会输出该由类中所有类属性组成的字典;而使用类的实例对象调用 __dict__,会输出由类中所有实例属性组成的字典。
举个例子: class CLanguage: a = 1 b = 2 def __init__ (self): self.name = "C语言中文网" self.add = "http://c.biancheng.net" #通过类名调用__dict__ print(CLanguage.__dict__) #通过类实例对象调用 __dict__ clangs = CLanguage() print(clangs.__dict__) 程序输出结果为: {'__module__': '__main__', 'a': 1, 'b': 2, '__init__': <function CLanguage.__init__ at 0x0000022C69833E18>, '__dict__': <attribute '__dict__' of 'CLanguage' objects>, '__weakref__': <attribute '__weakref__' of 'CLanguage' objects>, '__doc__': None}
{'name': 'C语言中文网', 'add': 'http://c.biancheng.net'}

不仅如此,对于具有继承关系的父类和子类来说,父类有自己的 __dict__,同样子类也有自己的 __dict__,它不会包含父类的 __dict__。例如: class CLanguage: a = 1 b = 2 def __init__ (self): self.name = "C语言中文网" self.add = "http://c.biancheng.net" class CL(CLanguage): c = 1 d = 2 def __init__ (self): self.na = "Python教程" self.ad = "http://c.biancheng.net/python" #父类名调用__dict__ print(CLanguage.__dict__) #子类名调用__dict__ print(CL.__dict__) #父类实例对象调用 __dict__ clangs = CLanguage() print(clangs.__dict__) #子类实例对象调用 __dict__ cl = CL() print(cl.__dict__) 运行结果为:
{'__module__': '__main__', 'a': 1, 'b': 2, '__init__': <function CLanguage.__init__ at 0x000001721A853E18>, '__dict__': <attribute '__dict__' of 'CLanguage' objects>, '__weakref__': <attribute '__weakref__' of 'CLanguage' objects>, '__doc__': None}
{'__module__': '__main__', 'c': 1, 'd': 2, '__init__': <function CL.__init__ at 0x000001721CD15510>, '__doc__': None}
{'name': 'C语言中文网', 'add': 'http://c.biancheng.net'}
{'na': 'Python教程', 'ad': 'http://c.biancheng.net/python'}

显然,通过子类直接调用的 __dict__ 中,并没有包含父类中的 a 和 b 类属性;同样,通过子类对象调用的 __dict__,也没有包含父类对象拥有的 name 和 add 实例属性。
除此之外,借助由类实例对象调用 __dict__ 属性获取的字典,可以使用字典的方式对其中实例属性的值进行修改,例如: class CLanguage: a = "aaa" b = 2 def __init__ (self): self.name = "C语言中文网" self.add = "http://c.biancheng.net" #通过类实例对象调用 __dict__ clangs = CLanguage() print(clangs.__dict__) clangs.__dict__['name'] = "Python教程" print(clangs.name) 程序运行结果为: {'name': 'C语言中文网', 'add': 'http://c.biancheng.net'}
Python教程

注意,无法通过类似的方式修改类变量的值。

关注公众号「 站长严长生 」,在手机上阅读所有教程,随时随地都能学习。内含一款搜索神器,免费下载全网书籍和视频。

微信扫码关注公众号
 
推荐文章