简体   繁体   English

我可以在python中有一个全局变量而不将其声明为全局变量吗?

[英]can I have a global variable in python without declaring it as global?

I want some sort of a global state that maintains the current number, as well as a function to generate the next number. 我想要某种维持当前数字的全局状态,以及生成下一个数字的函数。

I can write a generator to give me the next number. 我可以写一个生成器给我下一个数字。

 def gen(self, n):
    yield n
    yield n + 1

but what is a clean way to maintain its state? 但是什么是保持状态的干净方法呢? I do not want to simply have a global variable. 我不想简单地拥有一个全局变量。 Is there a better way to do this? 有一个更好的方法吗? or is that my only option? 还是我唯一的选择?

I tried to make a class like this: 我试图做这样的一堂课:

class Count:
"""
Represents the counter which
generates variables
"""

def __init__(self, curr=0):
    """
    :param curr: the current integer
    """
    self.curr = curr

def gen(self):
    """
    A generator for the next
    number
    :return: generator
    """
    self.curr += 1
    yield self.curr
    yield self.curr + 1

but this will not work, because every time I create Count(), it will reset my counter which I don't want. 但这将不起作用,因为每次创建Count()时,它将重置我不需要的计数器。

If my understanding is correct, to eliminate the global counter you could create a closure for you variable and return a function that increments it. 如果我的理解是正确的,则要消除global计数器,可以为变量创建一个闭包,然后返回一个递增其值的函数。

The original function counter is called only once, consecutive calls simply increment the counter: 原始功能counter仅被调用一次,连续调用仅使计数器递增:

def count(n):
    c = n
    def incr():
        nonlocal c
        c += 1
        print(c)
        return c
    return incr

count is initialized with some state n and incr references that state in consecutive calls: 使用一些状态n初始化count ,并在连续调用中声明该状态的incr引用:

>>> f = count(2)
>>> f()
3
>>> f()
4
>>> f()
5

Or you can use the next(generator) function. 或者,您可以使用next(generator)函数。

def num_gen():
    n=1
    while n:
        yield n
        n += 1

Then 然后

>>my_gen = num_gen()
>>next(my_gen)
1
>>next(my_gen)
2

And so forth. 依此类推。 Whenever a generator yields a value, the state of the generator is stored so that it can resume execution later. 每当生成器产生值时,都会存储生成器的状态,以便稍后可以恢复执行。

If you want to maintain state across multiple instances of Count , then use a variable in the class scope, and reference it with the Count. 如果要在Count多个实例之间维护状态,请在类范围内使用变量,并使用Count.引用它Count. prefix, like this: 前缀,像这样:

class Count:
    curr = 0

    def __init__(self, startWith = None):
        if startWith is not None: Count.curr = startWith - 1

    def gen(self):
        while True:
            Count.curr += 1
            yield Count.curr

Note that if you want to maintain state, the constructor should allow for the possibility to not reset the counter, but leave it untouched. 请注意,如果要保持状态,则构造函数应允许重置计数器,而保持原样。

As a side note, you might be interested in letting the generator generate a never ending series as shown above. 附带说明一下,您可能有兴趣让生成器生成一个永无止境的序列,如上所示。

Here is how you could use the above class: 这是使用上面的类的方法:

# Get generator that starts with 2
gen = Count(2).gen();

print (next(gen)); # -> 2
print (next(gen)); # -> 3
print (next(gen)); # -> 4

# Get a generator that continues ...
gen2 = Count().gen();

print (next(gen2)); # -> 5

# We can still use the previous generator also:

print (next(gen)); # -> 6

# Start with 0:

gen3 = Count(0).gen();

print (next(gen3)); # -> 0

# Other generators follow suit:

print (next(gen)); # -> 1
print (next(gen2)); # -> 2

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

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