How can I share a variable between functions in Python?
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)
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)
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.