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'>
posted @ 2021-08-27 16:45  LionYie  阅读(156)  评论(0)    收藏  举报