【问题标题】:python: Add a method with parameters with class decorator results in TypeError: add_bar() missing 1 required positional argument: 'cls'python:添加带有类装饰器参数的方法导致TypeError:add_bar()缺少1个必需的位置参数:'cls'
【发布时间】:2021-07-28 14:06:39
【问题描述】:

这是我的代码:

class MyInp(int):
    pass

def add_bar(cls, input_type):
    def bar(self, inp :input_type):
        print(f"bar: {inp}")

    setattr(cls, 'bar', bar)
    return cls

@add_bar(input_type=MyInp)
class Foo():
   pass

f = Foo()
f.bar(3)

运行返回:

TypeError: add_bar() 缺少 1 个必需的位置参数:'cls'

我知道我可以在类定义 (add_bar(Foo, MyInp)) 之后调用 add_bar,它会起作用 但是我如何添加一个需要多个参数的方法而不需要指定尚未定义的类? 还是我可以做一些别的事情,比如注册 input_type 并在定义类时以某种神奇的方式推断它的 input_type 并声明方法?

【问题讨论】:

    标签: python python-3.x python-decorators


    【解决方案1】:

    简短的回答是:

    class MyInp(int):
        pass
    
    def add_bar(input_type):
        def add_bar_impl(cls):
            def bar(self, inp :input_type):
                print(f"bar: {inp}")
    
            setattr(cls, 'bar', bar)
            return cls
        return add_bar_impl
    
    @add_bar(input_type=MyInp)
    class Foo():
       pass
    
    f = Foo()
    f.bar(3)
    

    不幸的是,法语版here提供了更长的解释......

    【讨论】:

    • 漂亮,所以基本上就像班级用add_bar_impl装饰?
    • 是的。 add_bar 只是一个返回实际装饰器 add_bar_impl 的函数。它的作用是将 input_type 变量放在 add_bar_impl 的闭包中。
    猜你喜欢
    • 2019-01-24
    • 2018-09-14
    • 2019-09-07
    • 2022-01-22
    • 2019-11-26
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多