程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

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

发布于2019-09-21 10:51     阅读(517)     评论(0)     点赞(16)     收藏(5)


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

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

index = 0

def foo():
    global index
    index += 1
    return index

三次调用该函数时:

print(foo())
print(foo())
print(foo())

它返回期望的值:

1
2
3

但是,我读到使用全局变量是一种不好的做法。因此,我想知道如果不使用全局变量就可以实现相同的结果。

有什么建议吗?

谢谢您的帮助。


解决方案


使用闭包:

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

inc = make_inc()
print inc()
print inc()
print inc()

使用类(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()

使用生成器(不可直接调用,您必须使用.next()方法):

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


inc = incgen()
print inc.next()
print inc.next()
print inc.next()


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:https://www.pythonheidong.com/blog/article/118015/45db9a305594c4c8af8e/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

16 0
收藏该文
已收藏

评论内容:(最多支持255个字符)