简体   繁体   English

一次函数中的python运行代码

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

I am trying to make a variable in Python go up by one continuously, but inside a function. 我试图使Python中的变量连续递增,但在函数内部。 What I am using is something like this: 我正在使用的是这样的:

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

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

I'm wondering if there is a much better way to do this? 我想知道是否有更好的方法可以做到这一点?

Probably the best way to do this is to put the definition of x and y into function 2, and have them be inputs and outputs of function 1. 可能最好的方法是将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)

Other alternatives include defining x and y globally and using global x , global y or using mutable default arguments to make the function retain state, but generally better to not resort to these options if you don't have to. 其他替代方法包括全局定义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()

A bit of code review and recommendations: 一点代码审查和建议:

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()

Looks like you want the function to count each time it is called. 看起来您希望函数在每次调用时都进行计数。 May I suggest something like this?: 我可以建议这样吗?:

x=5
y=10

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

def func2():
    while True:
        func1()

func2()

Better than using a global variable, stick them in a mutable object in a nested scope: 与使用全局变量相比,将它们粘贴在嵌套范围内的可变对象中更好:

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()

** just saw the edit on going up instead of down - modified code to suit** **只是看到了向上而不是向下的编辑-修改后的代码适合**

It's hard to tell from your question what your actual use case is but I think a Python generator may be the right solution for you. 从您的问题很难说出您的实际用例是什么,但是我认为Python生成器可能是您合适的解决方案。

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

Then to use: 然后使用:

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

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

This may be a slightly advanced for someone new to Python. 对于刚接触Python的人来说,这可能有点先进。 You can read up on generators here: http://anandology.com/python-practice-book/iterators.html 您可以在这里阅读生成器: http : //anandology.com/python-practice-book/iterators.html

First of all, the set1 function doesn't seem to do much at all, so you could take it away. 首先, set1函数似乎set1也没做,所以您可以将其删除。

If you want to keep count of the number of calls or keep state between calls, the best, more readable way is to keep this inside an object: 如果要计数调用次数或保持调用之间的状态,最好的,更具可读性的方法是将其保留在对象中:

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