【发布时间】:2019-08-08 00:30:54
【问题描述】:
我有以下 Python 元类,它为每个类添加了一个 deco_with_args 装饰器:
def deco_with_args(baz):
def decorator(func):
...
return func
return decorator
class Foo(type):
def __prepare__(name, bases):
return {'deco_with_args': deco_with_args}
这让我可以像这样使用装饰器:
class Bar(metaclass=Foo):
@deco_with_args('baz')
def some_function(self):
...
如何使deco_with_args 装饰器的行为类似于@classmethod,以便我可以从decorator 函数中访问Bar 类(或任何其他类)?
我尝试在deco_with_args 函数上使用@classmethod,但没有成功。
【问题讨论】:
-
您确定要使用元类来定义装饰器吗?
-
@DeepSpace 是有原因的。这是this question的后续行动。
-
Welp,我刚刚意识到这是不可能的。是时候重写我完成了 60% 的答案了……
-
澄清一下:您需要访问
test或decorator中的课程吗? -
就在
decorator里面。
标签: python python-3.x python-decorators metaclass class-method