0

I'm writing a method decorator and require access to the class defining the method that is currently decorated.

The issue seems with this is, that with Python 3 methods in a class are just functions unless the class is instantiated.

Is there any way around this? I don't really want to fiddle around with __qualname__...

In [29]: class A:
   ....:     def B(self):
   ....:         pass
   ....:     

In [30]: A.B.__qualname__
Out[30]: 'A.B'

# This is what I want:
>>> get_class(A.B)
A
4

1 回答 1

1

您不能,因为在运行方法上的装饰器时,尚未创建该类

一个例子更好地说明了这一点:

class Foo:
    @spam
    def bar(self): pass

spam(bar)被调用以生成修饰函数时,我们在 Python 运行以定义类主体的伪函数内部。只有当该伪函数执行完毕后,该函数的本地命名空间才会变成类体,并创建实际的类对象本身。

这意味着Foo在运行时还没有类对象spam()

相反,创建一个类装饰器:

@spam
class Foo:
    def bar(self): pass

现在spam()传递了整个完整Foo的类,使您可以访问该类和方法。

如果您需要在类上标记特定方法进行装饰,您可以使用标记装饰器来设置函数的属性:

def marker(func):
    func._marked = True
    return func

在你想要装饰的方法的类主体中使用这个装饰器,然后使用类装饰器来挑选这些方法:

@spam
class Foo:
    @marker
    def bar(self): pass

    def baz(self): pass
于 2013-10-15T17:40:52.917 回答