python3 给对象添加方法
import types
class Person:
def __init__(self,name):
self.name=name
def eat(self):
print('{}正在吃....'.format(self.name))
def run(self):
print('{}正在跑'.format(self.name))
p=Person('小明')
p.eat()
#给对象添加方法
p.run=types.MethodType(run,p) #将p当成参数传给run函数,然后赋值给p.run
p.run()
print(p.__dict__)
print(type(p.eat))
print(type(p.run))
#输出结果
小明正在吃....
小明正在跑
{'name': '小明', 'run': <bound method run of <__main__.Person object at 0x00000256B8D942B0>>}
<class 'method'>
<class 'method'>
本文来自博客园,作者:LionYie,转载请注明原文链接:https://www.cnblogs.com/LionYie/articles/15194372.html

浙公网安备 33010602011771号