Zahra
Zahra

Reputation: 7207

Recursive function as a static method

What is the right way of implementing a recursive function as a static method?

Here is how I have got it working atm. I was wondering if there is a "better" way of achieving this that leaves a cleaner memory footprint, looks more pythonic, etc.

class MyClass(object):
    @staticmethod
    def recursFun(input):
        # termination condition
        sth = MyClass().recursFun(subinput)
        # do sth
        return sth

Upvotes: 1

Views: 1300

Answers (2)

Lawrence D'Oliveiro
Lawrence D'Oliveiro

Reputation: 2804

Make it a classmethod instead:

class MyClass(object):

    @classmethod
    def recursFun(self, input):
        # termination condition
        sth = self.recursFun(subinput)
        # do sth
        return sth
    # end recursFun

#end MyClass

This also makes it easier to subclass the class, if you need to.

Upvotes: 1

chepner
chepner

Reputation: 532023

You don't require an instance of the class to perform the correct name lookup; the class itself will do.

class MyClass(object):
    @staticmethod
    def recursive_function(input):
        # ...
        sth = MyClass.recursive_function(subinput)
        # ...
        return sth

The qualified name is necessary because when you perform the name lookup, recursive_function won't be in scope; only MyClass.recursive_function will.

Upvotes: 6

Related Questions