Python静态变量生成器函数 [英] Python static variable generator function

查看:43
本文介绍了Python静态变量生成器函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下函数在 Python 中生成静态变量:

I am using the following function to generate a static variable in Python:

 #Static variable generator function
def static_num(self):
    k = 0
    while True:
        k += 1
        yield k

当我从主代码调用这个函数时:

When I am calling this function from main code:

 regression_iteration = self.static_num()
 print " Completed test number %s  %s \n\n" % (regression_iteration, testname)

我得到这个输出:

  "Completed test number <generator object static_num at 0x027BE260>  be_sink_ncq"

为什么我没有得到递增的整数?我的静态变量生成器哪里出错了?

Why I am not getting an incremented integer? Where is my static variable generator going wrong?

我现在以下列方式调用函数 static_num:

I am calling the function static_num in the following manner now:

regression_iteration = self.static_num().next()

但它只返回 '1',因为每次调用该函数时,'k' 的值都会被初始化为零.因此,我没有在每次调用函数时获得所需的输出 1,2,3,4 ....

But it returns only '1' since the value of 'k' is being initialized to zero every time the function is called. Therefore, I do not get the required output 1,2,3,4 .... on every call of the function

推荐答案

很难说你是否需要使用这种方法——我强烈怀疑它,但是您可以使用可变类型作为默认初始值设定项,而不是生成器:

Its hard to say whether you need to use this approach -- I strongly doubt it, but instead of a generator you could abuse using mutable types as default initializers:

def counter(init=[0]):
    init[0] += 1
    return init[0]

x = counter()
print(x)  # 1
print(x)  # 1
print(x)  # 1
x = counter()
print(x)  # 2
print(x)  # 2
print(x)  # 2
# ... etc

counter 的返回值在每次调用时加一,从 1 开始.

The return value of counter increases by one on each call, starting at 1.

这篇关于Python静态变量生成器函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆