python - 静态方法和递归?

标签 python class methods

我有以下代码:

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() 作为递归函数,它需要引用自身。但是,bar() 在一个类中,调用 return bar(n-1) 将不起作用,调用 NameError: global name 'bar' is not defined。我该如何处理这种情况?我是否应该将 bar() 更改为类或实例方法,以允许访问 selfcls

最佳答案

您可以通过在类名前加上前缀来引用 bar:

class Foo(object):
    def __init__(self):
        baz=self.bar(10)

    @staticmethod
    def bar(n):
        if n==0:
            return 'bar'
        else:
            return Foo.bar(n-1)

毕竟,静态方法只不过是包含在类的命名空间中的常规函数​​。

或者,将 bar 定义为常规函数:

def bar(n):
    if n==0:
        return 'bar'
    else:
        return bar(n-1)

class Foo(object):
    def __init__(self):
        baz=bar(10)

这完全避免了整个问题。

关于python - 静态方法和递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13183501/

相关文章:

python - 获取matplotlib中的数字列表

python - PyQt 5 - 显示 Py Designer GUI 的简单代码?

class - lua 类 - 无法设置属性和检索值

C# 数组方法帮助

java - 声明接口(interface)方法仅允许实现的类

python - 使用 python 在没有唯一标识符的情况下抓取 html

python - 无法使用pyodbc创建 Access 表

c# - DataAccess 项目中类的命名约定是什么?

c# - 使用事件序列化类

Java:非空方法作为映射值