How to Access Function variables in Another Function
I have a small issue while calling multiple variables in python one function to another. Like I have to access the variable of xxx() variables in yyy(). Help me to do this.?
Example :
def xxx():
a=10
b=15
c=20
def yyy():
xxx()
print a ### value a from xxx()
print b ### value b from xxx()
yyy()
Solution 1:
Return them from your first function and accept them in your second function. Example -
def xxx():
a=10
b=15
c=20
return a,b
def yyy():
a,b = xxx()
print a ### value a from xxx()
print b ### value b from xxx()
yyy()
Solution 2:
You can't. Variables created in a function are local to that function. So if you want function yyy
to get the values of some variables defined in function xxx
then you need to return them from xxx
, as demonstrated in Sharon Dwilif K's answer. Note that the names of the variables in yyy
are irrelevant; you could write:
def yyy():
p, q = xxx()
print p ### value a from xxx()
print q ### value b from xxx()
and it would give the same output.
Alternatively, you could create a custom class. Briefly, a class is a collection of data together with functions that operate on that data. Functions of a class are called methods, the data items are known as attributes. Each method of a class can have its own local variables, but it can also access the attributes of the class. Eg
class MyClass(object):
def xxx(self):
self.a = 10
self.b = 15
self.c = 20
def yyy(self):
self.xxx()
print self.a
print self.b
#Create an instance of the class
obj = MyClass()
obj.yyy()
output
10
15
Please see the linked documentation for more information about classes in Python.
Solution 3:
Try this:
def xxx():
a=10
b=15
c=20
return a, b
def yyy():
a, b = xxx()
print a
print b
yyy()
Or this:
def xxx():
global a, b
a=10
b=15
c=20
def yyy():
print a
print b
xxx()
yyy()
For more info, use help('return')
and help('global')
, or see this and this question.
And only use global
when you need the variable can use at everywhere or you need the function return other things. Because modifying globals will breaks modularity.