问题
I have 2 functions fun1
and fun2
which take as inputs a string and a number respectively. The also both get as input the same variable a
. This is the code:
a = ['A','X','R','N','L']
def fun1(string,vect):
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)
The functions perform some nonsense operations. My goal would be to rewrite the code in such a way that the variable a is shared between the functions so that they do not take it as input anymore.
One way to remove variable a
as input would be by defining it within the functions themselves but unfortunately that is not very elegant.
Could you suggest me a possible way to reach my goal?
The functions should operate in the same way but the input arguments should only be the string and the number (fun1(string)
, fun2(number)
).
回答1:
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)
回答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
回答3:
Since a
is define outside the function scope and before the functions are defined, you do not need to feed it as argument, you can simply use a
. Python will first look whether the variable is defined in the function scope, 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)
来源:https://stackoverflow.com/questions/41636867/how-to-share-variable-between-functions-in-python