如何用Python装饰器模式基于字典动态为类添加方法?
基于装饰器模式为类批量动态添加方法
需求背景
现有基类Animal,以及存储方法的字典methods(键为方法名,值为对应函数),需要通过装饰器模式批量将字典中的方法动态添加到Animal类中。此前尝试的标准装饰器只能单个添加方法,无法实现批量操作,期望通过一行代码完成批量添加。
现有代码定义
方法字典:
methods = { "walk": lambda self: print(f"{self.name} is walking"), "run": lambda self: print(f"{self.name} is running"), }
基类:
class Animal: def __init__(self, name): self.name = name
解决方案
实现一个接收方法字典作为参数的装饰器工厂,遍历字典中的键值对,将每个函数绑定为目标类的方法,即可通过一行装饰器代码完成批量添加。
完整实现代码
def add_methods(methods_dict): def decorator(cls): # 遍历方法字典,为类批量绑定方法 for method_name, method_func in methods_dict.items(): setattr(cls, method_name, method_func) return cls return decorator # 一行代码完成批量方法添加 @add_methods(methods) class Animal: def __init__(self, name): self.name = name # 测试功能 dog = Animal("旺财") dog.walk() # 输出:旺财 is walking dog.run() # 输出:旺财 is running
代码说明
add_methods是装饰器工厂函数,接收方法字典作为参数,返回负责修改类的装饰器函数。- 内部的
decorator函数通过setattr遍历字典,将每个函数绑定为目标类的属性(即类的方法)。 - 用
@add_methods(methods)修饰Animal类,即可一次性完成所有方法的动态添加。
内容的提问来源于stack exchange,提问作者user21122547
相关产品推荐
相关产品推荐

