Make staticmethod call itself without calling self.method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | def recursive(func):
func.func_globals[func.__name__] = func
return func
class Test:
def method(self, x = False):
if x:
print(x)
else:
self.method("I'm method")
@staticmethod
def smethod(x = False):
if x:
print(x)
else:
method("I'm static method")
@staticmethod
@recursive
def rmethod(x = False):
if x:
print(x)
else:
rmethod("I'm recursive method")
test = Test()
test.method() # I'm method
test.rmethod() # I'm recursive method
test.smethod() # raises NameError: global name 'method' is not defined
|
please correct me if it can be done better
Tags: decorators, staticmethod
Download
Copy to clipboard
You can access static methods through the class.
e.g Test.smethod()
If you want the name to be global, just write the function at global scope.
You could adapt the Y-Combinator function to work with the static method to give you recursion without nested calls in the source :-)