Discuss / Python / 为什么通过动态绑定类的实例方法,不能修改实例属性?

为什么通过动态绑定类的实例方法,不能修改实例属性?

Topic source

fromtypesimportMethodType

classStudent(object):

def__init__(self, *args, **kwargs):

self.name= kwargs.pop('name')

self.age= kwargs.pop('age')

self.score= kwargs.pop('score')

defset_score(self, value):

self.score = value

defget_score(self):

returnself.score

Student.set_score =MethodType(set_score, Student)

Student.get_score =MethodType(get_score, Student)

t=Student(name="Bryan", age=24, score=80)

# 输出80

print(t.score)

t.set_score(100)

# 输出100

print(t.get_score())

# 为什么这里还是输出80,而不是100?

print(t.score)


  • 1

Reply