vks
vks

Reputation: 67968

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.

Upvotes: 1

Views: 646

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122382

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.

Upvotes: 4

Horia Coman
Horia Coman

Reputation: 8781

The class decorator is being applied to the class itself, and it is applied only once, when the class is defined. Basically, it processes the class definition and produces a new class.

So you'd only process it once.

Upvotes: 2

Related Questions