1

I have a base class, in which I want to define a decorator. That decorator should be used in inheriting classes.

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

When doing it like this, I'm getting the message model_definition() missing 1 required positional argument: 'self'. What is the correct way to do it?

user1406177
  • 1,328
  • 2
  • 22
  • 36
  • Also related: https://stackoverflow.com/questions/2365701/decorating-python-class-methods-how-do-i-pass-the-instance-to-the-decorator – r.ook Jan 16 '19 at 15:03

1 Answers1

1

model_definition method needs an instance, that's what the parameter self stands for. Now, in order to use a decorator on an instance, you could simply pass the instance as a parameter. Here is an example where the decorator is static :

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)

Main :

l = Lower()

I am defining the model

('The model is : ', 'example_model')

madjaoue
  • 5,104
  • 2
  • 19
  • 31
  • If you're just using a static method as a decorator why put it in a class at all? – r.ook Jan 16 '19 at 15:16
  • Readability, and logic. I guess that's why you still have @staticmethod decorator. However, it's true that the decorator could be defined outside the class. – madjaoue Jan 16 '19 at 15:17