简单函数返回每次调用时递增1的数字,没有全局变量?

Baa*_*ooo 8 python increment

我正在尝试编写一个python函数,在第一次调用时,返回1.在第二次调用时,返回2.在第三个,一个3.等等.

目前,我使用全局变量实现了这一目标:

index = 0

def foo():
    global index
    index += 1
    return index
Run Code Online (Sandbox Code Playgroud)

调用该函数三次时:

print(foo())
print(foo())
print(foo())
Run Code Online (Sandbox Code Playgroud)

它返回预期的值:

1
2
3
Run Code Online (Sandbox Code Playgroud)

但是,我已经读过使用全局变量是不好的做法.所以,我想知道如果不使用全局变量可以实现相同的结果.

有什么建议吗?

谢谢您的帮助.

bru*_*ers 11

使用闭包:

def make_inc():
    val = [0]
    def inc():
        val[0] += 1
        return val[0]
    return inc

inc = make_inc()
print inc()
print inc()
print inc()
Run Code Online (Sandbox Code Playgroud)

使用类(OOPL中最明显的解决方案):

class Inc(object):
    def __init__(self):
        self._val = 0

    def __call__(self):
        self._val += 1
        return self._val


inc = Inc()
print inc()
print inc()
print inc()
Run Code Online (Sandbox Code Playgroud)

使用生成器(不能直接调用,你必须使用该.next()方法):

def incgen():
    val = 0
    while True:
        val += 1
        yield val


inc = incgen()
print inc.next()
print inc.next()
print inc.next()
Run Code Online (Sandbox Code Playgroud)


Ser*_*aev 6

您可以使用函数属性:

def f():
    f.counter = getattr(f, 'counter', 0) + 1
    return f.counter
Run Code Online (Sandbox Code Playgroud)

或关闭:

def w():
    counter = 0
    def f():
        nonlocal counter
        counter += 1
        return counter
    return f
Run Code Online (Sandbox Code Playgroud)