Self-referencing inside class definition

不问归期 提交于 2019-12-01 17:56:05

You cannot, because during class definition, the class does not yet exist.

You can apply the decorator after the class has been created:

class A():
    def f(self):
        return 2

    def w(self, f):
        return fr + 5 

A.f = dec(A.w)(A.f.__func__)

or you can swap the order of the two method definitions and refer to w as a local name still:

class A():
    def w(self, f):
        return fr + 5 

    @dec(w)
    def f(self):
        return 2

In both cases you are passing in a callable A.w that is not bound to an instance. No self will be passed in, so you need to add that yourself, in the decorator:

def decorate(w):
    def _wrap(f):
        def _call(self, *args, **kwargs):
            return w(self, f(*args, **kwargs))
        def _call
    return _wrap

If you didn't expect w to be bound (it acting as a static method instead), you could just use a normal function instead here.

Generally speaking, creating a decorator to call another method on the same instance is somewhat pointless; why not just call w from within f, directly?

class A():
    def f(self):
        return self.w(2)

    def w(self, f):
        return fr + 5 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!