Discuss / Python / 老师的讲解示例无法运行

老师的讲解示例无法运行

Topic source

Colorful

#1 Created at ... [Delete] [Delete and Lock User]

根据老师的正文示例,写下如下代码给Student类添加一个方法:

from types import MethodType

class Student(object):
    pass

def set_score(self, score):
    self.score = score

s = Student()
s2 = Student()

Student.set_score = set_score

s.set_score(100)
print(s.score)
print(s2.score)

但会报错:

Traceback (most recent call last):
  File "c:\...\slotstemp.py", line 17, in <module>
    print(s2.score)
AttributeError: 'Student' object has no attribute 'score'

如果将

Student.set_score = set_score

换为

Student.set_score = MethodType(set_score, Student)

就可以运行了,输出

100

100

请问给Student类添加方法时,Student.set_score = set_score 和 Student.set_score = MethodType(set_score, Student) 有什么不同?谢谢

ANFANDAAAR

#2 Created at ... [Delete] [Delete and Lock User]

Student.set_score = MethodType(set_score, Student),会产生覆盖,后面的对象的score会把前面的对象覆盖。

匪号鴻源

#3 Created at ... [Delete] [Delete and Lock User]

你之前给类添加方法是没有给s2赋值,所以报错。

修改后不报错因为MethodType方法把第一个输出的score当作了类属性。Student.score也会是100

ap

#4 Created at ... [Delete] [Delete and Lock User]

应该是这样理解:

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

Reply