分别给Python类和实例增加属性和方法

zhuquan0 2020-05-25

#定义一个类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‘

相关推荐