python store variable in function and use it later

前端 未结 5 1497
星月不相逢
星月不相逢 2021-02-06 18:01

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

for eg:during while loop, p

5条回答
  •  执念已碎
    2021-02-06 18:53

    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.

提交回复
热议问题