老师的讲解示例无法运行
Topic source应该是这样理解:
def set_score(self, score):
self.score = score
Student.set_score = set_score
这个就相当于直接在 'Student' 这个 'class' 中添加一个类方法 'Student.set_score', 这时这个类方法中的 'self' 指的是 'Student' 类的(创建后的) **实例** .
def set_score(self, score):
self.score = score
Student.set_score = MethodType(set_score, Student)
此时, 'Student' 是被当做一个 'type' 类的一个 **实例** , 给 'Student' 这个(type类的)实例添加了一个实例方法 'Student.set_score', 这时这个实例方法中的 'self' 指的是
'Student' 本身, 也就相当于是'Student.score = score'.
- 1
Colorful
根据老师的正文示例,写下如下代码给Student类添加一个方法:
但会报错:
如果将
换为
就可以运行了,输出
100
100
请问给Student类添加方法时,Student.set_score = set_score 和 Student.set_score = MethodType(set_score, Student) 有什么不同?谢谢