且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

类内部定义的自引用

更新时间:2023-02-02 23:33:00

您不能,因为在类定义期间,该类尚不存在。 / p>

您可以在创建类后应用装饰器:

 类别A():
def f(自):
返回2

def w(自已,f):
返回fr + 5

Af = dec(Aw)(Af__func__)

,也可以交换两种方法定义,并仍以本地名称引用 w

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

@dec(w)
def f(self):
返回2

在两种情况下,您都传递了可调用的 Aw 未绑定到实例的/ code>。没有 self 会被传入,因此您需要在装饰器中添加自己:

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

如果您没想到 w 会受 约束(它起着静态方法的作用),您可以在这里使用普通函数代替。 / p>

通常来说,创建装饰器以在同一实例上调用另一个方法 毫无意义;为什么不从 f 内部直接调用 w ,直接

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

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


How do I reference class object inside class definition? Could you advice me how you would do it? Or more specifically how do you pass class object inside decorator of class method? Here is a simple example, I'm trying to pass second method I'm declaring to decorator of first one.

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

class A():

    @dec(A.w)
    def f():
        return 2

    def w(f):
        return fr + 5 

As expected exception is raised

NameError: name 'A' is not defined

As a result of my investigation i learned that globals() doesn't contain A key while i'm inside decorate or _wrap functions, but defined inside _call. So I could probably find passed method by string name (e.g @dec('A.w')), but in that case it is impossible to cache method search inside _wrap closure.

So how do you fix that? :)

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