Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

What does python's return statement actually return?

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:

def foo():
    y = 5
    return y

When invoking foo(), we get the value 5.

x = foo()

x binds the integer object 5.

What does it mean? 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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...