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()
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With