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

如何使用装饰器在Python中动态创建类方法?

实现基于配置的动态类方法装饰器

直接上可运行的实现代码,完全匹配你的需求:

def dynamic_methods(method_config):
    def decorator(cls):
        # 遍历配置字典,将每个方法绑定到类上
        for method_name, method_impl in method_config.items():
            setattr(cls, method_name, method_impl)
        return cls
    return decorator

# 你的方法配置
method_config = {
    'method1': lambda self: "This is method1",
    'method2': lambda self, arg: f"Method2 received {arg}"
}

@dynamic_methods(method_config)
class MyClass:
    pass

# 测试
obj = MyClass()
print(obj.method1())  # 输出: This is method1
print(obj.method2("test arg"))  # 输出: Method2 received test arg

关键说明

  • 装饰器dynamic_methods是带参数的装饰器,先接收方法配置字典,再返回真正处理类的装饰器函数。
  • 内部的decorator函数负责遍历配置,用setattr把每个方法实现绑定到目标类上——这是Python中动态修改类属性的标准方式。
  • 配置中的lambda必须包含self作为第一个参数(除非定义静态方法,见扩展),因为类的实例方法默认会把实例本身作为第一个参数传入。

扩展场景处理

如果需要添加类方法或静态方法,只要在配置里对实现做对应包装即可:

method_config_extended = {
    'instance_method': lambda self: "I'm instance method",
    'class_method': classmethod(lambda cls: "I'm class method"),
    'static_method': staticmethod(lambda: "I'm static method")
}

@dynamic_methods(method_config_extended)
class MyClass2:
    pass

obj2 = MyClass2()
print(obj2.instance_method())  # 输出: I'm instance method
print(MyClass2.class_method())  # 输出: I'm class method
print(MyClass2.static_method())  # 输出: I'm static method

注意事项

  • 如果配置中的方法名和类原有方法重名,配置中的方法会覆盖原有方法,使用时要注意避免命名冲突。
  • 除了lambda,你也可以用普通函数作为方法实现,比如:
    def complex_method(self, x, y):
        return x + y
    
    method_config = {
        'add': complex_method
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 14:04:54