python use multiple values in multiple function

前端 未结 1 719
粉色の甜心
粉色の甜心 2020-12-22 12:40

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         


        
相关标签:
1条回答
  • 2020-12-22 13:12

    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.

    >>> def func1():
    ...     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:

    # dict
    def func1():
        return {'x': 2, 'y': 3}
    
    def funcx():
        print(func1()['x'])
    
    # namedtuple
    from collections import namedtuple
    
    Point2D = namedtuple('Point2D', ['x', 'y'])
    def func1():
        return Point2D(x=2, y=3)
    
    def funcx():
        print(func1().x)
    
    0 讨论(0)
提交回复
热议问题