This question already has answers here:
Python class method decorator with self arguments?
                                
                                    (5个答案)
                                
                        
                                去年关闭。
            
                    
我有一个基类,我想在其中定义一个装饰器。该装饰器应在继承类中使用。

class Upper(object):
    def model_definition(self, name):
        def func(create_function):
            if self.loading:
                model = self.load(name)
            else:
                model = create_function()

            self.models[name] = model
            return model
        return func

class Lower(Upper):
    @Upper.model_definition(name='example_model'):
    def define_model(self):
        [...]
        return model


这样做时,我收到消息model_definition() missing 1 required positional argument: 'self'。正确的方法是什么?

最佳答案

model_definition方法需要一个实例,这就是参数self所代表的含义。
现在,为了在实例上使用装饰器,您只需将实例作为参数传递即可。这是一个装饰器是静态的示例:

class Upper(object):
    def __init__(self):
        self.model = None

    @staticmethod
    def model_definition(name=''):
        def func(f):
            def wrapper(*args):
                self = args[0]
                print('I am defining the model')
                if not self.model:
                    self.model = name
                return f(*args)

            return wrapper

        return func

class Lower(Upper):
    def __init__(self):
        Upper.__init__(self)
        self.define_model()

    @Upper.model_definition(name='example_model')
    def define_model(self):
        print('The model is : ', self.model)


主要:

l = Lower()



  我正在定义模型
  
  (“模型为:”,“ example_model”)

关于python - 带有参数的继承类方法修饰器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54219595/

10-15 02:03