You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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

代码说明

  1. add_methods是装饰器工厂函数,接收方法字典作为参数,返回负责修改类的装饰器函数。
  2. 内部的decorator函数通过setattr遍历字典,将每个函数绑定为目标类的属性(即类的方法)。
  3. 用@add_methods(methods)修饰Animal类,即可一次性完成所有方法的动态添加。

内容的提问来源于stack exchange,提问作者user21122547

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 03:55:15