Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can subclasses in Python inherit parent class decorator

Tags:

If I apply a decorator to a class:

from flask.ext.restful import Resource

@my_decorator()
class Foo(Resource): ...

Will it be automatically applied to any subclass methods as well? For example, will it be magically applied to a_foobar_method?

class FooBar(Foo):

    def a_foobar_method(self):
        ...
like image 954
user1658296 Avatar asked Oct 12 '16 15:10

user1658296


1 Answers

In short, no.

@my_decorator
class Foo(Resource): ...

is simply shorthand for

class Foo(Resource): ...
Foo = my_decorator(Foo)

If the only time you ever use Foo is to define FooBar, then together your two pieces of code are equivalent to this:

class Foo(Resource): ...
Foo_decorated = my_decorator(Foo)
class FooBar(Foo_decorated):
    def a_foobar_method(self):
        ...

Or even to this:

class Foo(Resource): ...
class FooBar(my_decorator(Foo)):
    def a_foobar_method(self):
        ...

The real answer depends on what the decorator does. In principle it stands a chance of seeing the methods of FooBar if it looks at the list of methods after the class has been instantiated as an object (e.g. because it modifies the __init__ method). But if it goes through the methods at the time it is called and applies some change to each of them, then it will have no effect on extra methods (or replaced methods) in FooBar.

like image 68
Arthur Tacca Avatar answered Sep 26 '22 16:09

Arthur Tacca