Python动态添加类属性

Python动态添加类属性教程

Python 是动态语言,因此 Python 可以在运行时改变自身结构,动态添加和删除 属性 和方法。

Python动态添加类属性详解

语法

class Student: pass Student.attr = value

说明

我们可以直接使用 “类名.属性 = 值” 的形式,给类动态地添加一个类属性。

案例

动态添加类属性

给 Python 中的类动态添加属性

print("嗨客网(www.haicoder.net)") class Student: score = 99.95 def __init__(self): pass Student.course = "Python" stu = Student() stu1 = Student() print("Course =", stu.course, "Score =", stu.score) print("Course =", stu1.course, "Score =", stu1.score)

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

17_python动态添加类属性.png

我们创建了一个类 Student,接着,为该类添加了一个类属性 score,和一个 __init__ 方法。

接着,我们为类 Student 动态添加了一个名为 course 的类属性,并且赋值为 “Python”。

最后,我们创建了两个 Student 类的实例,并通过实例来调用类属性,可以看出,两个实例都有了我们动态添加的类属性。

动态添加类属性

给 Python 中的类动态添加属性

print("嗨客网(www.haicoder.net)") class Student: score = 99.95 def __init__(self): pass stu = Student() stu1 = Student() Student.course = "Python" print("Course =", stu.course, "Score =", stu.score) print("Course =", stu1.course, "Score =", stu1.score)

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

18_python动态添加类属性.png

我们先创建了两个类的实例,接着,再次为类动态的增加类属性,最后,再次访问动态添加的类属性,可以访问。因此,动态添加类属性的顺序与实例化类的顺序无关。

Python动态添加类属性总结

Python 是动态语言,因此 Python 可以在运行时改变自身结构,动态添加和删除类的属性和方法。Python 动态添加类属性语法:

class Student: pass Student.attr = value

我们可以直接使用 “类名.属性 = 值” 的形式,给类动态地添加一个类属性。