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)

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

我们创建了一个类 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)

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

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

Python动态添加类属性总结

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

class Student:

pass

Student.attr = value

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值