通過 types 模塊動(dòng)態(tài)添加實(shí)例方法和類方法的實(shí)踐筆記
import types
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def speak_age(self):
print(f"age is {self.age}")
def speak_name(self):
print(f"name is {self.name}")
@staticmethod
def add_static_method():
print("call add_static_method")
@classmethod
def add_class_method(cls):
print("call add_class_method")
if __name__ == "__main__":
tom = Person("tom", 30)
tom.speak_age()
# 添加實(shí)例方法,并調(diào)用
tom.speak_name = types.MethodType(speak_name, tom)
tom.speak_name()
# 添加靜態(tài)方法
Person.add_static_method = add_static_method
# 添加類方法
Person.add_class_method = add_class_method
tom.add_static_method()
tom.add_class_method()
# 新實(shí)例依然可以調(diào)用
ana = Person("ana", 18)
ana.add_static_method()
運(yùn)行后控制臺(tái)輸出

image.png