Welcome, guest | Sign In | My Account | Store | Cart

Make staticmethod call itself without calling self.method

Python, 31 lines
 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

3 comments

Will McGugan 12 years, 4 months ago  # | flag

You can access static methods through the class.

e.g Test.smethod()

Gabriel Genellina 12 years, 4 months ago  # | flag

If you want the name to be global, just write the function at global scope.

Paddy McCarthy 12 years, 4 months ago  # | flag

You could adapt the Y-Combinator function to work with the static method to give you recursion without nested calls in the source :-)

Created by bazooka on Fri, 10 Jul 2009 (MIT)
Python recipes (4591)
bazooka's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks