from types import MethodType
class Student(object):
def __init__(self, *args, **kwargs):
self.name = kwargs.pop('name')
self.age = kwargs.pop('age')
self.score = kwargs.pop('score')
def set_score(self, value):
self.score = value
def get_score(self):
return self.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)
print(isinstance(Student, object)) #True
原因解析
Student.set_score = MethodType(set_score, Student)
姑且这么认为:MethodType是一个可调用对象用于将静态函数对象绑定到实例对象上成为实例方法,Student本身是类也可以认为是object基类的实例,所以Student实例的score属性并不影响另一个实例t的score属性。
#MethodType源码
class MethodType:
__func__: _StaticFunctionType
__self__: object
__name__: str
__qualname__: str
def __init__(self, func: Callable[..., Any], obj: object) -> None: ...
def __call__(self, *args: Any, **kwargs: Any) -> Any: ...