python 给对象添加方法

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'>
写出漂亮的博客就是为了以后看着更方便的。
原文地址:https://www.cnblogs.com/zhaowei5/p/10251157.html