How can I share a variable between functions in Python?

前端 未结 5 767
一个人的身影
一个人的身影 2021-02-13 16:18

I have two functions, fun1 and fun2, which take as inputs a string and a number, respectively. They also both get the same variable, a, as

5条回答
  •  难免孤独
    2021-02-13 16:46

    Object Oriented Programming and making a a member variable is absolutely the best solution here.

    But sometimes you have codes that are not OO, think of a flask application for example when you have multiple endpoints that you'd like to share some value. In this case, a shared or global variable is the way to go. Meaning defining the varibale outside the scope of all the methods so it could be accessed anywhere.

    Now, if the value of your variable never changes, you sould use uppercase letters for naming, to mark it as final and in a sense global (similar to final static variables in Java).

    A = ['A','X','R','N','L']

    But if the value does change, first, the name should be lowercase a = ['A','X','R','N','L']. Second, you'd want to limit the places where the value can change, ideally to only one method, and there you can use the global keyword to change the value

    a = ['A','X','R','N','L']
    
    def fun1(string,vect):
        global a
        a.append('W')
    
        out = []
        for letter in vect:
            out. append(string+letter)
        return out
    
    def fun2(number,vect):
        out = []
        for letter in vect:
            out.append(str(number)+letter)
        return out
    
    x = fun1('Hello ',a)
    y = fun2(2,a)
    

    If you find yourself changing the value of a in multiple places in your code, a shared/global variable is probably not what you're looking for and instead you should just pass the value around as a parameter.

提交回复
热议问题