Python类__dict__属性

Python类__dict__属性教程

Python 中的 ,都会从 object 里继承一个 __dict__ 属性,这个属性中存放着类的 属性方法 对应的键值对。一个类 实例化 之后,这个类的实例也具有 __dict__ 属性。

Python 类中的 __dict__ 属性是以 字典 的形式存放着属性和方法,键为属性名,值为属性的值。

案例

实例方法访问类属性

实例方法使用 self 访问类属性

print("嗨客网(www.haicoder.net)") class Student: course = "Python" def __init__(self, name, age): self.name = name self.age = age print("Student dict =", Student.__dict__) stu = Student("William", 18) print("stu dict =", stu.__dict__) stu.score = 99 print("stu dict =", stu.__dict__)

程序运行后,控制台输出如下:

41_python类dict属性.png

我们创建了一个类 Student,并且为该类添加了一个类属性 course,一个 构造函数,接受额外的 name 属性和 age 属性。

接着,我们直接使用类名访问其 __dict__ 属性,类的 __dict__ 属性包含了类属性 course,以及类层次的属性,比如 __module____init__ 等。

最后,我们创建了一个 Student 类的实例 stu,接着,访问实例 stu 的 __dict__ 属性,我们发现,实例 stu 的 __dict__ 属性只有 name 和 age,并且是以属性名做为键属性值做为值的形式存储。

我们再次,给实例 stu 添加了一个 动态属性,此时,再次访问实例的属性,动态属性已经存在类实例中。

实例方法访问类属性

实例方法使用 self 访问类属性

print("嗨客网(www.haicoder.net)") class Student: def __init__(self): pass def info(self): print("call instance method") @classmethod def hello(cls): print("call class method") @staticmethod def thx(): print("call static method") print("Student dict =", Student.__dict__) stu = Student() print("stu dict =", stu.__dict__)

程序运行后,控制台输出如下:

42_python类dict属性.png

我们创建了一个类 Student,并且为该类添加了一个构造函数,一个 实例方法 info,一个 类方法 hello 以及一个静态方法 thx。

接着,我们直接使用类名访问其 __dict__ 属性,类的 __dict__ 属性包含了上述的所有方法。

最后,我们创建了一个 Student 类的实例 stu,接着,访问实例 stu 的 __dict__ 属性,我们发现,实例 stu 的 __dict__ 属性为空。

实例方法访问类属性

实例方法使用 self 访问类属性

print("嗨客网(www.haicoder.net)") class Student: course = "Python" def __init__(self, name, age): self.name = name self.age = age def info(self, name, age): print("call instance method, name =", name, "age =", age) @classmethod def hello(cls): print("call class method, course =", cls.course) @staticmethod def thx(): print("call static method") print("Student dict =", Student.__dict__) stu = Student("haicoder", 18) print("stu dict =", stu.__dict__) print("Student Course =", Student.__dict__["course"]) print("stu name =", stu.__dict__["name"]) print("stu age =", stu.__dict__["age"])

程序运行后,控制台输出如下:

43_python类dict属性.png

我们可以在类的 __dict__ 属性和实例的 __dict__ 属性里面传入我们需要访问的类属性或者实例属性的名字,即可访问其具体的值。

Python类__dict__属性总结

Python 中的类,都会从 object 里继承一个 __dict__ 属性,这个属性中存放着类的属性和方法对应的键值对。一个类实例化之后,这个类的实例也具有 __dict__ 属性。

Python 类中的 __dict__ 属性是以字典的形式存放着属性和方法,键为属性名,值为属性的值。