What does python's return statement actually return?

后端 未结 2 1587
情深已故
情深已故 2020-12-20 10:23

I want to know how we get the value returned by a function - what the python return statement actually returns.

Considering following piece of code:



        
相关标签:
2条回答
  • 2020-12-20 10:59

    x binds the integer object 5.

    Yes, x is a variable holding a reference to the integer object 5, which y also holds the reference to.

    What does the return statement actually return here? The int object 5? Or variable name y? Or the binding to the object 5? Or something else?

    To be precise, it is the reference to integer object 5 being returned. As an example, look at this:

    In [1]: def foo():
       ...:     y = 5
       ...:     print(id(y))
       ...:     return y
       ...: 
    
    In [2]: x = foo()
    4297370816
    
    In [3]: id(x)
    Out[3]: 4297370816
    

    How do we get the value returned by the return statement?

    By accessing the reference that return passes back to the caller.

    0 讨论(0)
  • 2020-12-20 11:07

    If you have any doubts you can always go to Python's REPL and experiment with values and functions. There is a type() instruction that can be used with values as well as with functions, for example:

    Python 3.6.2 (default, Jul 19 2017, 13:09:21) 
    [GCC 7.1.1 20170622 (Red Hat 7.1.1-3)] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> def foo():
    ...     y=5
    ...     return y
    ... 
    >>> type(foo())
    <class 'int'>
    

    Regarding your foo() function, y is a local binding that holds the value int. return statement returns a value of variable y and this binding is not known outside the foo() function scope.

    0 讨论(0)
提交回复
热议问题