[英]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 x
, global 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.