MethodType函数可以把外部函数绑到一个类和实例中,但在使用过程中发现一些问题,故写这篇博客记录下自己在操作过程中的发现和分析结果。(Python3.7.6)
1.类方法与实例方法
首先要知道类方法与实例方法的区别,直接引用我觉得写的很不错一篇文章:
Python 实例方法、类方法、静态方法的区别与作用
2.公共代码
# _*_ coding : utf-8 _*_
from types import MethodType
class Student(object):
pass
def set_score(self, score):
self.score = score
3.用MethodType把set_score函数绑到类的指定实例上
s1 = Student()
s2 = Student()
s1.set_score = MethodType(set_score,s1)
s1.set_score(