0

考虑以下情况:

class test:
  def foo(self, o):
    print(o)

  @staticmethod
  def bar(o):
    print(o)
    
  @classmethod
  def qux(cls, o):
    print(cls)
    print(o)

def baz(o):
  print(o)

t = test()

class A:
  meth1 = t.bar
  meth2 = t.foo
  meth3 = baz
  meth4 = t.qux

a = A()
a.meth1()
a.meth3()
# a.meth4()
# a.meth2()

这工作得很好,但是如果我打电话,meth2/4我会收到以下错误:

TypeError: <foo/qux>() missing 1 required positional argument: 'o'

有什么办法可以让我像t.fooand一样工作吗?t.quxt.barbaz

4

1 回答 1

0

meth4in 在A这里不被视为类方法,因为您尚未将其定义为这样。

类方法使用装饰器语法声明,如下所示:

@decorator
def func(x, y):
    return z

它本质上定义了一个函数func,然后调用decorator它。

因此,您实际上可以这样做meth4 = classmethod(t.qux),并且效果很好。

对于meth2,我不确定你预期会发生什么。它是一个self隐式接受并接受参数的实例方法o,所以当你调用a.meth2时,当然需要指定一个参数o

于 2021-07-07T04:22:50.243 回答