【问题标题】:Decorate class method with another class method用另一个类方法装饰类方法
【发布时间】: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 时,将引发异常,因为该函数被传递给selffunc 没有任何内容。但我不能只用staticmethod 装饰foo,因为运行wrapped 函数需要self

这是一个两难的选择。有人可以帮忙吗?

【问题讨论】:

  • 该示例在 Foobar 的 定义 期间失败,因为仅使用一个参数调用 foo:bar。您无法创建实例,因为类定义永远不会完成。
  • @jonrsharpe 我知道。我的意思是,我怎样才能将实例传递给foo
  • 为什么需要? wrapped 被 self 调用,因为它替换了 bar。
  • @jonrsharpe 啊。
  • 查看我的答案以获得解决方案。

标签: python class methods python-decorators


【解决方案1】:

foo() 方法中不能有self,但可以通过在wrapped() 函数中指定它来获取:

class Foobar:
    def foo(func):
        print('foo is running')
        def wrapped(self, *args, **kwargs):
            print(str(self) + " is doing something")
            func(self, *args, **kwargs)
        return wrapped
    @foo
    def bar(self, *args, **kwargs):
        print("Foobar")
        print(self, args, kwargs)

print('Make Foobar')
f = Foobar()
f.bar(1, f=42)
print('Done')

为了清楚起见,我添加了一些 print() 语句,以便您查看操作顺序:

foo is running
Make Foobar
<__main__.Foobar object at 0x03BE5210> is doing something
Foobar
<__main__.Foobar object at 0x03BE5210> (1,) {'f': 42}
Done

【讨论】:

  • 你真的应该把方法放在类之外。
猜你喜欢
  • 2021-12-26
  • 2019-11-02
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 2018-08-15
  • 1970-01-01
  • 2014-01-14
  • 2011-07-03
相关资源
最近更新 更多