简体   繁体   English

Python:增加全局变量的优雅方式

[英]Python: Elegant way to increment a global variable

Elegant way to increment a global variable in Python:在 Python 中增加全局变量的优雅方法:

This is what I have so far:这是我到目前为止:

my_i = -1
def get_next_i():
    global my_i
    my_i += 1
    return my_i

with generator:带发电机:

my_iter = iter(range(100000000)) 
def get_next_i():
    return next(my_iter)

with class:与班级:

class MyI:
    MyI.my_i = -1
    @staticmethod
    def next():
        MyI.my_i += 1
        return MyI.my_i
  • The first one is long and I don't consider it as a better way to code .第一个很长,我不认为它是更好的编码方式。
  • The second one is a bit more elegant, but have an upper limit.第二个更优雅一点,但有一个上限。
  • The third one is long, but at least have no global variable to work with.第三个很长,但至少没有全局变量可以使用。

What would be the best alternative to those?什么是最好的替代品?

The purpose of these functions is to assign a unique number to a specific event in my code.这些函数的目的是为我的代码中的特定事件分配一个唯一编号。 The code is not just a single loop, so using for i in range(...): is not suitable here.代码不仅仅是一个循环,所以for i in range(...):使用for i in range(...):不适合这里。 A later version might use multiple indices assigned to different events.更高版本可能会使用分配给不同事件的多个索引。 The first code would require duplication to solve such an issue.第一个代码需要重复才能解决这样的问题。 ( get_next_i() , get_next_j() , ...) ( get_next_i() , get_next_j() , ...)

Thank You.谢谢你。

As others suggested, itertools.count() is the best option, eg正如其他人所建议的, itertools.count()是最好的选择,例如

import itertools

global_counter1 = itertools.count()
global_counter2 = itertools.count()
# etc.

And then, when you need it, simply call next :然后,当你需要它时,只需调用next

def some_func():
    next_id = next(global_counter1)

EDIT: Changed global_counter1.next() (which worked only in Python 2) to next(global_counter1) , which works also in Python 3.编辑:global_counter1.next() (仅适用于 Python 2)更改为next(global_counter1) ,它也适用于 Python 3。

You can create a generator that has an infinite loop.您可以创建一个具有无限循环的生成器。 Each call of next(generator) will return a next value, without limit.每次调用next(generator)都会返回一个下一个值,没有限制。 See What does the "yield" keyword do in Python?请参阅Python 中的“yield”关键字有什么作用?

def create_generator()
    i=0
    while True:
        i+=1
        yield i

generator = create_generator()
print(next(generator))
print(next(generator))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM