Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #63513

Understanding decorator and class methods

Newsgroups comp.lang.python
Date 2014-01-08 11:56 -0800
Message-ID <d4d38119-b5b8-415a-bb7b-5d544907df3e@googlegroups.com> (permalink)
Subject Understanding decorator and class methods
From axis.of.weasel@gmail.com

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Understanding decorator and class methods axis.of.weasel@gmail.com - 2014-01-08 11:56 -0800
  Re: Understanding decorator and class methods Rotwang <sg552@hotmail.co.uk> - 2014-01-08 23:17 +0000
  Re: Understanding decorator and class methods Terry Reedy <tjreedy@udel.edu> - 2014-01-08 19:20 -0500

csiph-web