vks vks - 1 month ago 8
Python Question

Class decorator not being called everytime

A seemingly easy thing which i cant get around.

registry = {}

def register(cls):
registry[cls.__clsid__] = cls
print cls
return cls

@register
class Foo(object):
__clsid__ = "123-456"

def bar(self):
pass
c=Foo()
d=Foo()

e=Foo()


Output:

<class '__main__.Foo'>


Now i expect decorator to be called
3
times.Why has it been called only
once
.

Answer

A class decorator is applied when the class is created, not each time an instance is created.

The @register line applies to the class Foo(object): statement only. This is run just once, when the module is imported.

Creating an instance does not need to re-run the class statement because instances are just objects that keep a reference to the class (type(c) returns the Foo class object); instances are not 'copies' of a class object.

If you want to register instances you'll either have to do so in the __init__ or the __new__ method of a class (which can be decorated too). __new__ is responsible for creating the instance, __init__ is the hook called to initialise that instance.