给实例添加或者修改成员函数
import types
class People():
def __init__(self):
self.age=10
self.name='Bob'
def show_age(self):
print(self.age)
def show_name(self):
print(self.name)
def show_age_new(self):
print(self.age+1)
p=People()
p.show_name = types.MethodType(show_name,p)
p.show_name()
p.show_age = types.MethodType(show_age_new,p)
p.show_age()
给类添加或者修改成员函数
class People():
def __init__(self):
self.age=10
self.name='Bob'
def show_age(self):
print(self.age)
def show_name(self):
print(self.name)
def show_age_new(self):
print(self.age+1)
People.show_age = show_age_new
p=People()
p.show_age() '''等效于People.show_age(p)'''
p=People()
如果用
p.show_age = show_age_new
再调用
p.show_age()
会报缺少参数,没找出什么原因
把修改前后的show_age进行变量查看
p=People()
print(type(p.show_age)) # <class 'method'>
p.show_age = show_age_new
print(type(p.show_age)) # <class 'function'>
说明赋值进去的成员函数其实上已经变成了一个普通的函数
但是如果用
p.show_age(p)
又是可以正常显示的,暂时不知道为什么