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):
        def inner(self):
            print('f called')
            return f(self)
        return inner

    def f(self):

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

c = C()
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


Reply via email to