Understanding decorator and class methods

axis.of.weasel at gmail.com axis.of.weasel at gmail.com
Wed Jan 8 14:56:42 EST 2014


can someone please explain why the following works, in contrast to the second example?

def decorator(func):
    def on_call(*args):
        print args  
        return func(args)
    return on_call

class Foo:
    @decorator
    def bar(self, param1):
        print 'inside bar'

f=Foo()
f.bar(4)  # from where is the decorator getting the Foo instance?



I understand why the following works/does not work

class decorator2:
    def __init__(self, func):
        self.func=func
    def __call__(self, *args):
        self.func(*args)

class Foo2:
    @decorator2
    def bar2(self, param): pass


f2 = Foo2()
Foo2.bar2(f2, 4) # works, Foo2 instance and param are passed to decorator2 call
f2.bar2(4) # does not work, Foo2 instance is missing, decorator2 cannot invoke method bar



More information about the Python-list mailing list