I try to give the user the possibility to choose which function to use for a class.
Snippet 1
Something like this:
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))
However, I get
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
When I remove the @staticmethod
, it works. Why is that the case? I thought without the decorator, the first argument would always be self
or cls
?
Why doesn't snippet 1 work?
Snippet 2
This one, however, works:
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))