I’m trying to decorate a class with another class. I also want to inherit from the decorated class, but I get some errors. Here’s my code:
class Decorator:
def __init__(self, decorated):
pass
@Decorator
class Foo:
pass
class Goo(Foo):
pass
The error I get when I try to subclass from Foo is this:
Traceback (most recent call last):
File “test.py”, line 9, in
class Goo(Foo):
TypeError: __init__() takes exactly 2 positional arguments (4 given)
By adding another init function to Decorator…
def __init__(self, *args):
for arg in args:
print(arg)
… I get the following output:
<class ‘__main__.Foo’>
Goo
(<__main__.Decorator object at 0x010073B0>,)
{‘__module__’: ‘__main__’}
What are those parameters and how should I be using them inside Decorator?
I’ll try to answer the “what are those parameters” question. This code:
is equivalent to:
This means that
Fooends up being an instance of theDecoratorclass instead of being a class.When you try to use this instance as a base of a class (
Goo), Python will have to determine a metaclass that will be used to create the new class. In this case it will useFoo.__class__which equals toDecorator. Then it will call the metaclass with(name, bases, dict)arguments and expect it to return a new class.This is how you end up with these arguments in
Decorator.__init__.More about this can be found here:
http://www.python.org/download/releases/2.2.3/descrintro/#metaclasses
(particularly the “When a class statement is executed…” part)