为了方便用户查看类中包含哪些属性,Python 类提供了 __dict__ 属性。需要注意的一点是,该属性可以用类名或者类的实例对象来调用,用类名直接调用 __dict__,会输出该由类中所有类属性组成的字典;而使用类的实例对象调用 __dict__,会输出由类中所有实例属性组成的字典。
举个例子:
class CLanguage:
a = 1
b = 2
def __init__ (self):
self.name = ""
self.add = "http://zhishitu.com"
#通过类名调用__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': '', 'add': 'http://zhishitu.com'}
不仅如此,对于具有继承关系的父类和子类来说,父类有自己的 __dict__,同样子类也有自己的 __dict__,它不会包含父类的 __dict__。例如:
class CLanguage:
a = 1
b = 2
def __init__ (self):
self.name = ""
self.add = "http://zhishitu.com"
class CL(CLanguage):
c = 1
d = 2
def __init__ (self):
self.na = "Python教程"
self.ad = "http://zhishitu.com/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': '', 'add': 'http://zhishitu.com'}
{'na': 'Python教程', 'ad': 'http://zhishitu.com/python'}
除此之外,借助由类实例对象调用 __dict__ 属性获取的字典,可以使用字典的方式对其中实例属性的值进行修改,例如:
class CLanguage:
a = "aaa"
b = 2
def __init__ (self):
self.name = ""
self.add = "http://zhishitu.com"
#通过类实例对象调用 __dict__
clangs = CLanguage()
print(clangs.__dict__)
clangs.__dict__['name'] = "Python教程"
print(clangs.name)
程序运行结果为:{'name': '', 'add': 'http://zhishitu.com'}
Python教程
注意,无法通过类似的方式修改类变量的值。