Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Access Function variables in Another Function

Tags:

python

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()
like image 852
3 revs Avatar asked Dec 01 '22 00:12

3 revs


2 Answers

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()
like image 104
Sharon Dwilif K Avatar answered Jan 25 '23 22:01

Sharon Dwilif K


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.

like image 25
PM 2Ring Avatar answered Jan 25 '23 22:01

PM 2Ring