Read variables under return function using variable name

85 views Asked by At
>>> class test():
...     def add(self):
...         a = 3+5
...         b = 4+9
...         return a,b
...     
>>> x = test()
>>> x.add()
(8, 13)
>>> z = x.add()
>>> z[0]
8
>>> z[1]
13

I looking for way to read individual variable like value of a and b using variable name not z[0] or z[1].

I am also trying to avoid using global variables.

4

There are 4 answers

0
rook On

You can also use a kind of this shamanism:

class wrap:
    def __init__(self, **data):
        self.__dict__.update(data)

def named(m):
    def f(self):
        a,b = m(self)
        return wrap(**{'a': a, 'b': b})
    return f

class test:
    @named
    def add(self):
        a = 3+5
        b = 4+9
        return a,b

it decorates your method with dictonary (thus, named values) and tranpose them to the properties of the object, i.e. it will work as:

t = test()
x = t.add()

print x.a, x.b
3
thefourtheye On

Simply assign like this

a, b = x.add()

Now, a will have 8 and b will have 13

0
James Mills On

You can used collections.namedtuple() for this:

from collections import namedtuple


Values = namedtuple("Values", ["a", "b"])


class Test():

    def add(self):
        a = 3 + 5
        b = 4 + 9

        return Values(a=a, b=b)


test = Test()
x = test.add()
print x.a
print x.b

Output:

8
13

You could also just return a dict. e.g:

def add():
    a = 3 + 5
    b = 4 + 9

    return {"a": a, "b": b}

Which you would then access via the Python syntactic sugar [key], e.g:

x["a"]
x["b"]

Or you could simply unpack the returned unnamed tuple like so:

a, b = test.add()
0
Aromal Sasidharan On

tuples can be unpacked and stored in variable also

for eg.

x,y,z = 2,3,4
def getMyTuple():
   return a,b,c,d

w,x,y,z = getMyTuple()