Python __dict__属性:查看对象内部所有属性名和属性值组成的字典

Python018

Python __dict__属性:查看对象内部所有属性名和属性值组成的字典,第1张

在 Python 类的内部,无论是类属性还是实例属性,都是以字典的形式进行存储的,其中属性名作为键,而值作为该键对应的值。

为了方便用户查看类中包含哪些属性,Python 类提供了 dict 属性。需要注意的一点是,该属性可以用类名或者类的实例对象来调用,用类名直接调用 dict ,会输出该由类中所有类属性组成的字典;而使用类的实例对象调用 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 。例如:

运行结果为:

{' 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 属性获取的字典,可以使用字典的方式对其中实例属性的值进行修改,例如:

程序运行结果为:

{'name': 'C语言中文网', 'add': ' http://c.biancheng.net' }

Python教程

类属性:

class Employee(object):

emCount=0

def __init__(self,name,salary):

self.nane=name

self.salary=salary

类属性就是定义类的时候直接定义的属性 emCount,类似于java里面的static修饰的属性,可以直接通过 类名.属性名访问:Employee.emCount

实例属性是在__init()方法中定义的属性,例如name,和salary,self是指向自己的,类似java的this关键字,实际是通过内置的方法setattr()完成的

可以通过重写setatttr()进行类属性的增加和获取