0

I've a base class and a child class. Base class has a class variable which is passed to decorator. Now, when I inherit Base into child, and change the variable value, the decorator does not take the over-ride class variable value.

Here's the code:-

class Base():   
    variable = None

    @decorator(variable=variable)
    def function(self):
        pass

class Child(Base):
    variable = 1

Without overriding the function again: How do I pass child class variable to the decorator?

petezurich
  • 9,280
  • 9
  • 43
  • 57
Praful Bagai
  • 16,684
  • 50
  • 136
  • 267
  • 1
    See https://stackoverflow.com/a/1133013/476. `...=variable` is evaluated right there and then. It does not dynamically refer to `self.variable` or `cls.variable` or anything like that. – deceze Nov 01 '18 at 06:56

1 Answers1

0

The comment from deceze already explained why this is not getting reflected on the sub classes.

One workaround is, you can build the logic on the decorator side.

Ie, something like this.

 def decorator(_func=None, *, variable):
    def decorator_func(func):
        def wrapper(self, *args, **kwargs):
            variable_value = getattr(self.__class__, variable)
            print(variable_value)
            # You can use this value to do rest of the work.
            return func(self, *args, **kwargs)
        return wrapper

    if _func is None:
        return decorator_func
    else:
        return decorator_func(_func)

Also update the decorator syntax from @decorator(variable=variable) to @decorator(variable='variable')

class Base:

    variable = None

    @decorator(variable='variable')
    def function(self):
        pass

DEMO

b = Base()
b.function() # This will print `None`.

Lets try with the subclass

b = Child()
b.function() # This will print `1`.
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46