分别给Python类和实例增加属性和方法
2021-01-11 00:32
标签:object eth from python pass rom type core imp 分别给Python类和实例增加属性和方法 标签:object eth from python pass rom type core imp 原文地址:https://www.cnblogs.com/nyist-xsk/p/12956991.html#定义一个类Student
class Student(object):
pass
#给类增加一个属性name
Student.name = ‘xm‘
print Student.name # xm
#给类增加一个方法set_age
def set_age(self,age):
self.age = age
Student.set_age = set_age
s = Student()
s.set_age(20)
print s.age #20
#给实例属性增加一个属性:
s1 = Student()
s1.name = ‘xh‘
print s1.name #xh
#给实例属性增加一个方法:
def set_score(self,score):
self.score = score
from types import MethodType
s1.set_score = MethodType(set_score,s1)
s1.set_score(88)
print s1.score #88
#而其它的实例对象并没有set_score方法
print s.score #‘Student‘ object has no attribute ‘score‘
文章标题:分别给Python类和实例增加属性和方法
文章链接:http://soscw.com/index.php/essay/41338.html