簡體   English   中英

一次函數中的python運行代碼

[英]python run code that is in a function once

我試圖使Python中的變量連續遞增,但在函數內部。 我正在使用的是這樣的:

def func1():
   def set1():
      x=5
      y=10
   ##lots of code
   x+=1
   y+=1

def func2():
   while True:
      func1()
set1()
func2()

我想知道是否有更好的方法可以做到這一點?

可能最好的方法是將x和y的定義放入函數2中,並使它們成為函數1的輸入和輸出。

def func1(x, y):
    ##lots of code
    x+=1
    y+=1
    return x, y

def func2():
    x = 5
    y = 10
    while True:
        x, y = func1(x, y)

其他替代方法包括全局定義x和y並使用global xglobal y或使用可變的默認參數來使函數保留狀態,但是通常最好不要使用這些選項。

x = None
y = None

def set1():
    global x, y
    x=5
    y=10

def func1():
    global x, y
    x+=1
    y+=1

def func2():
    while True:
        func1()
set1()
func2()

一點代碼審查和建議:

def func1():
   def set1():
      x=5
      y=10
   ##lots of code
   x+=1
   y+=1

def func2():
   while True:
      func1()

set1() # This won't work because set1 is in the local scope of func1
       # and hidden from the global scope
func2()

看起來您希望函數在每次調用時都進行計數。 我可以建議這樣嗎?:

x=5
y=10

def func1():
    global x, y
    x+=1
    y+=1
    print x, y

def func2():
    while True:
        func1()

func2()

與使用全局變量相比,將它們粘貼在嵌套范圍內的可變對象中更好:

Counts = dict(x=5, y=10)

def func1():
    Counts['x'] += 1
    Counts['y'] += 1
    print Counts['x'], Counts['y']

def func2():
    while True:
        func1()

func2()

**只是看到了向上而不是向下的編輯-修改后的代碼適合**

從您的問題很難說出您的實際用例是什么,但是我認為Python生成器可能是您合適的解決方案。

def generator(x, y):
    yield x,y
    x += 1
    y += 1

然后使用:

if __name__ == "__main__":
    my_gen = generator(10,5)

    for x,y in my_gen:
        print x,y
        if x+y > 666:
            break

對於剛接觸Python的人來說,這可能有點先進。 您可以在這里閱讀生成器: http : //anandology.com/python-practice-book/iterators.html

首先, set1函數似乎set1也沒做,所以您可以將其刪除。

如果要計數調用次數或保持調用之間的狀態,最好的,更具可讀性的方法是將其保留在對象中:

class State(object):
    def __init__(self):
        self._call_count = 0
        self.x = 5

    def func1(self):
        self._call_count += 1
        self.x =  ... Whatever

def func2():
    state = State()
    while True:
        state.func1()

暫無
暫無

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

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