问题描述
考虑以下情况:
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()
TypeError: <foo/qux>() missing 1 required positional argument: 'o'
有什么办法可以让 t.foo
和 t.qux
像 t.bar
和 baz
一样工作吗?
解决方法
meth4
中的 A
在这里不被视为类方法,因为您还没有这样定义它。
类方法使用装饰器语法声明,如下所示:
@decorator
def func(x,y):
return z
本质上定义了一个函数 func
,然后对其调用 decorator
。
因此,您实际上可以只执行 meth4 = classmethod(t.qux)
,而且效果很好。
对于meth2
,我不确定您预期会发生什么。它是一个实例方法,它隐式地接受self
并接受一个参数o
,所以当你调用a.meth2
时,当然需要指定一个参数o
。