使用类方法或按名称调用类(如其他人所示)的替代方法是使用闭包来保存对函数的引用:
class Foo(object):
def bar():
def bar(n):
if n == 0:
return "bar"
return bar(n-1)
return bar
bar = staticmethod(bar())
The (minor) advantage is that this is somewhat less susceptible to breaking when names change. For example, if you have a reference to Foo.bar
inside bar
, this relies on Foo
continuing to be a global name for the class that bar
is defined in. Usually this is the case but if it isn't, then the recursive call breaks.
The classmethod
approach 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.