我尽力使用户可以选择用于类的功能。
类似这样的东西:
class TestFoo():
@staticmethod
def foo(x, y):
return x * y
methodstr2method = {'foo': foo}
def __init__(self, method_str):
self.method = self.methodstr2method[method_str]
def exec(self, x, y):
return self.method(x, y)
a = TestFoo('foo')
print(a.exec(3, 7))
但是我知道
Traceback (most recent call last):
File "/home/math/Desktop/foobar.py", line 17, in <module>
print(a.exec(3, 7))
File "/home/math/Desktop/foobar.py", line 13, in exec
return self.method(x, y)
TypeError: 'staticmethod' object is not callable
当我移除@staticmethod
时,它可以工作。为什么会这样?我以为没有装饰器,第一个参数将始终是self
或cls
?
为什么代码段1无效?
但是,此方法有效:
class TestFoo():
@staticmethod
def foo(x, y):
return x * y
def __init__(self, method_str):
self.methodstr2method = {'foo': self.foo}
self.method = self.methodstr2method[method_str]
def exec(self, x, y):
return self.method(x, y)
a = TestFoo('foo')
print(a.exec(3, 7))