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


Groups > comp.lang.python > #72893

Re: Decorating one method of a class C with another method of class C?

From Terry Reedy <tjreedy@udel.edu>
Subject Re: Decorating one method of a class C with another method of class C?
Date 2014-06-06 21:34 -0400
References <CAGGBd_pM5DGp85LVfeQgYwqS8DU8nuQL8Q8G5EzfQ5BX26fa-w@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.10839.1402104871.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 6/6/2014 8:14 PM, Dan Stromberg wrote:
> Is there a way of decorating method1 of class C using method2 of class C?
>
> It seems like there's a chicken-and-the-egg problem; the class doesn't
> seem to know what "self" is until later in execution so there's
> apparently no way to specify @self.method2 when def'ing method1.

Class code is executed in a new local namespace, which later becomes the 
class attribute space. So you can (sort of), but I cannot see a reason 
to do so.

class C:
     def deco(f):
         print('decorating')
         def inner(self):
             print('f called')
             return f(self)
         return inner

     @deco
     def f(self):
         print(self)

     del deco  # because it is not really a method
     # but rather an undecorated static method

c = C()
c.f()
 >>>
decorating
f called
<__main__.C object at 0x000000000348B898>

If deco is decorated as a staticmethod, it has to be called on the class 
or an instance thereof after the class is constructed. If deco is 
defined outside the class, it can be used both inside and outside.

-- 
Terry Jan Reedy

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


Thread

Re: Decorating one method of a class C with another method of class C? Terry Reedy <tjreedy@udel.edu> - 2014-06-06 21:34 -0400

csiph-web