I have following code:
class Foo(object):
def __init__(self):
baz=self.bar(10)
@staticmethod
def bar(n):
if n==0:
return 'bar'
else:
return bar(n-1)
bar() as a recursive function it needs reference to itself. However, bar() is inside a class, and calling return bar(n-1) will not work, invoking NameError: global name 'bar' is not defined. How can I deal with this kind of situation? Should I change bar() to a class or instance method, allowing access to self or cls?
An alternative to using a class method or calling the class by name (as shown by others) is to use a closure to hold the reference to the function:
The (minor) advantage is that this is somewhat less susceptible to breaking when names change. For example, if you have a reference to
Foo.barinsidebar, this relies onFoocontinuing to be a global name for the class thatbaris defined in. Usually this is the case but if it isn’t, then the recursive call breaks.The
classmethodapproach will provide the method with a reference to the class, but the class isn’t otherwise needed in the method, which seems inelegant. Using the closure will also be marginally faster because it isn’t doing an attribute lookup on each call.