简体   繁体   English

python在函数中存储变量并在以后使用它

[英]python store variable in function and use it later

is it possible to store a variable from a while loop to a function and then call that same variable from the function at the end of the loop 是否可以将while循环中的变量存储到函数中,然后在循环结束时从函数中调用该变量

for eg:during while loop, problem here is that when i try to retrieve the variable from store() it fails...as it needs arguments to be passed.. 例如:在while循环期间,问题在于当我尝试从store()检索变量时它失败了......因为它需要传递参数。

def store(a,b,c):
    x1 = a
    y1 = b
    z1 = c
    return (x1,y1,z1)

def main():
    while condition:
          x = .......
          y = .......
          z = .......
          ......
          ......
          store(x,y,z) #store to function...
          ......
          ......
          ......
          s1,s2,s3 = store()
          ......
          ......
          ......

As others have stated, there is probably a more suitable choice than this, but it might be convenient in some situations (perhaps in a REPL). 正如其他人所说,可能有一个比这更合适的选择,但在某些情况下(可能在REPL中)可能会很方便。 Here's a simple function that does what you want with any number of values. 这是一个简单的函数,可以使用任意数量的值执行您想要的操作。

def store(*values):
    store.values = values or store.values
    return store.values
store.values = ()

Example

>>> store(1, 2, 3)
>>> a, b, c = store()
>>> print a, b, c
1 2 3
>>> store(4, 5)
>>> a, b = store()
>>> print a, b
4 5

Hmmm, unless I am misunderstanding, this is a classic non-solution to a non-problem. 嗯,除非我误解,这是一个非问题的经典非解决方案。

Why not just use the language as it is? 为什么不直接使用这种语言呢?

while condition:

   x = something
   y = else
   z = altogether
   ...
   save_state = (x,y,z)   ## this is just a python tuple.
   ...
   # do something else to x, y and z, I assume
   ...
   x, y, z = save_state

Depending on the type of x , y and z you may have to be careful to store a copy into the tuple. 根据xyz的类型,您可能必须小心将copy存储到元组中。

(Also, your indentation is wrong, and there is no such thing as end in python.) (另外,你的缩进是错误的,并且在python中没有end这样的东西。)

Update: Ok, if I understand better, the question is just to be able to use the previous value the next time through. 更新:好的,如果我理解得更好,问题就是能够在下次通过时使用之前的值。 In the simplest case, there is no problem at all: the next time through a loop, the the value of x , y , and z are whatever they were at the end of the previous time through the loop (this is the way all programming languages work). 在最简单的情况下,根本没有问题:下一次循环时, xyz是它们在前一次循环结束时的任何值(这是所有编程的方式)语言工作)。

But if you want to be explicit, try something like this: 但如果你想明确,请尝试这样的事情:

 x_prev = some_starting_value
 x = some_starting_value
 while condition:
      x = something_funky(x_prev)

      .... other stuff ....

      x_prev = x

(but again, note that you don't need x_prev at all here: x=something_funky(x) will work.) (但请再次注意,这里根本不需要x_prevx=something_funky(x)将起作用。)

Technically speaking, if you had a deep, burning desire to do this with functions, you can always do it with a closure (which is, as we all know, a poor man's object): 从技术上讲,如果你有一个深刻的,强烈的愿望用函数来做这件事,你总是可以用一个闭包(就像我们所知,一个穷人的对象)来做:

def store(a,b,c):
    def closure():
        return (a,b,c)
    return closure

stored = store(1,2,3)
print stored()

prints in (1,2,3) 打印(1,2,3)

As much as this is a bad idea I like applying weird solutions so here 尽管这是一个坏主意,但我喜欢在这里应用奇怪的解决方案

class Store(object):
    def __init__(self, f):
        self.f = f
        self.store = None

    def __call__(self, *args):
        self.store = self.f(*args)

@Store        
def test(a,b,c):
    return a+b+c

print test(1,2,3)
print test.store

Decorate the function with Store then call function.store to get what you called in it, if the function is never called it returns a single None, you could make it raise an exception but personally I didn't want to. 用Store装饰函数然后调用function.store来获取你在其中调用的内容,如果函数从未调用它返回一个None,你可以使它引发异常,但我个人并不想这样做。

No, you can't do this. 不,你不能这样做。

Also, it's a terrible, terrible idea. 此外,这是一个可怕的,可怕的想法。 "Store to a function" is such an awful and wrong thing to do that I hesitate to provide working code. “存储到函数”是一件非常糟糕的事情,我不愿意提供工作代码。

Use a callable object. 使用可调用对象。

class Store( object ):
    def __init__( self ):
        self.x, self.y, self.z = None, None, None
    def __call__( self, x=None, y=None, z=None ):
        if x is None and y is None and z is None:
            return self.x, self.y, self.z
        else:
            self.x, self.y, self.z = x, y, z

What's better is to do something simpler that doesn't involve a function with magical properties that does two different things when called with and without arguments. 更好的是做一些更简单的事情,不涉及具有魔法属性的函数,当使用和不使用参数调用时,它会执行两个不同的事情。

Anything is better than "store to a function". 任何东西都比“存储功能”更好。 Anything. 任何东西。

Really. 真。

Anything. 任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM