簡體   English   中英

Python靜態變量生成器函數

[英]Python static variable generator function

我正在使用以下函數在Python中生成靜態變量:

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

當我從主代碼調用此函數時:

 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"

為什么我沒有得到遞增的整數? 我的靜態變量生成器哪里出問題了?

編輯:

我現在以以下方式調用函數static_num:

regression_iteration = self.static_num().next()

但是它僅返回“ 1”,因為每次調用該函數時,“ k”的值都被初始化為零。 因此,在每次調用該函數時,我都沒有得到所需的輸出1,2,3,4 ....

很難說是否需要使用這種方法-我對此表示強烈懷疑,但是除了生成器之外,您還可以濫用可變類型作為默認初始化器:

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開始增加1。

yield關鍵字將函數返回值從int轉換為int生成器,因此必須使用“ for self in in self.static_num()”來訪問int。如果要一一訪問生成器。 使用下一個功能。

假設用static表示對類靜態,那么做到這一點的最佳方法是使用類變量和classmethod

class Static_Number_Class(object):
    _static_number = 0
    @classmethod
    def static_number(cls):
        cls._static_number += 1
        return cls._static_number

如果這只是一個獨立的函數,則可以使用閉包代替:

def Counter():
    n = 0
    def inner():
        n += 1
        return n
    return inner

count = Counter()
x = count()
print(x) # 1
x = count()
print(x) # 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM