How can I share a variable between functions in Python?

前端 未结 5 777
一个人的身影
一个人的身影 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.

    0 讨论(0)
  • 2021-02-13 16:48

    Object-oriented programming helps here:

    class MyClass(object):
        def __init__(self):
            self.a = ['A','X','R','N','L']  # Shared instance member :D
    
        def fun1(self, string):
            out = []
            for letter in self.a:
                out.append(string+letter)
            return out
    
        def fun2(self, number):
            out = []
            for letter in self.a:
                out.append(str(number)+letter)
            return out
    
    a = MyClass()
    x = a.fun1('Hello ')
    y = a.fun2(2)
    
    0 讨论(0)
  • 2021-02-13 16:48

    This can be easily achieved using the global keyword. That makes the a variable available in the whole file. However, the global variables should be avoided as much, because every function has access to these, it becomes increasingly hard to figure out which functions actually read and write these variables.

    a = ['A','X','R','N','L']
    
    def fun1(string):
        out = []
        for letter in a:
            out. append(string+letter)
        return out
    
    def fun2(number):
        out = []
        for letter in a:
            out.append(str(number)+letter)
        return out
    
    x = fun1('Hello ')
    y = fun2(2,a)
    
    0 讨论(0)
  • 2021-02-13 16:49

    An alternative to using classes: You can use the global keyword to use variables that lie outside the function.

    a = 5
    def func():
        global a
        return a+1
    
    print (func())
    

    This will print 6.

    But global variables should be avoided as much as possible.

    0 讨论(0)
  • 2021-02-13 16:50

    Since a is defined outside the function scope and before the functions are defined, you do not need to feed it as an argument. You can simply use a.

    Python will first look whether the variable is defined in the function scope, and if not, it looks outside that scope.

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

    In this case you can also rewrite your functions into more elegant list comprehensions:

    a = ['A','X','R','N','L']
    
    def fun1(string):
        return [string+letter for letter in a]
    
    def fun2(number):
        return [str(number)+letter for letter in a]
    
    x = fun1('Hello ')
    y = fun2(2)
    
    0 讨论(0)
提交回复
热议问题