【发布时间】:2021-10-23 07:37:39
【问题描述】:
假设我有一个类,我想用另一个方法装饰它的一个方法。就像在示例中一样:
class Foobar:
def foo(self, func):
def wrapped(*args, **kwargs):
print(self + " is doing something")
func(*args, **kwargs)
return wrapped
@foo
def bar(self, *args, **kwargs):
print("Foobar")
当然,当我创建Foobar 的实例并运行bar 时,将引发异常,因为该函数被传递给self 而func 没有任何内容。但我不能只用staticmethod 装饰foo,因为运行wrapped 函数需要self。
这是一个两难的选择。有人可以帮忙吗?
【问题讨论】:
-
该示例在 Foobar 的 定义 期间失败,因为仅使用一个参数调用 foo:bar。您无法创建实例,因为类定义永远不会完成。
-
@jonrsharpe 我知道。我的意思是,我怎样才能将实例传递给
foo? -
为什么需要? wrapped 被 self 调用,因为它替换了 bar。
-
@jonrsharpe 啊。
-
查看我的答案以获得解决方案。
标签: python class methods python-decorators