1. 给对象添加方法
# 方法1
class Student1():
pass
def desc():
print("这是外部方法")
st1 = Student1()
st1.desc1 = desc
st1.desc1()
# 方法2
import types
def run(self): # 注意有参数中有self
print("学生再跑")
st1.run1 = types.MethodType(run, st1)
st1.run1()
2.给类添加方法
class Student2():
def desc(self):
print("对象方法")
pass
@classmethod
def fun(cls):
print("类方法")
# 添加
Student2.fun = fun
st2 = Student2()
# 使用对象调用
st2.fun()
# 使用类调用
Student2.fun()