Python Use Multiple Values In Multiple Function
How to do something like this in python def func1(): x = 2 y = 3 return x, y def funcx(): print(func1().x) def funcy(): print(func1().y) So basically return
Solution 1:
Python functions can return only one value, but it is easy for that value to contain others. In your example, func1
returns a single tuple, which in turn contains two values.
>>>deffunc1():... x = 2... y = 3...return x, y...>>>func1()
(2, 3)
You can index or unpack this return value just like any other tuple:
>>>func1()[0]
2
>>>func1()[1]
3
>>>a, b = func1()>>>a
2
You can use indexing also in your desired functions:
def funcx():
print(func1()[0])
def funcy():
print(func1()[1])
If you desire named fields, you can use a dict
or namedtuple
:
# dictdeffunc1():
return {'x': 2, 'y': 3}
deffuncx():
print(func1()['x'])
# namedtuplefrom collections import namedtuple
Point2D = namedtuple('Point2D', ['x', 'y'])
deffunc1():
return Point2D(x=2, y=3)
deffuncx():
print(func1().x)
Post a Comment for "Python Use Multiple Values In Multiple Function"