Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in Python to return a value via an output parameter?

Tags:

python

Some languages have the feature to return values using parameters also like C#. Let’s take a look at an example:

class OutClass {     static void OutMethod(out int age)     {         age = 26;     }     static void Main()     {         int value;         OutMethod(out value);         // value is now 26     } } 

So is there anything similar in Python to get a value using parameter, too?

like image 904
Leonid Avatar asked Jan 15 '11 21:01

Leonid


People also ask

How do you return a Output in Python?

The Python return statement is a special statement that you can use inside a function or method to send the function's result back to the caller. A return statement consists of the return keyword followed by an optional return value. The return value of a Python function can be any Python object.

Does a parameter return a value?

The parameter is a string in which you will count the words. The argument is any string you pass to your function when you call it. The return value is the number of words.


2 Answers

There is no reason to, since Python can return multiple values via a tuple:

def func():     return 1,2,3  a,b,c = func() 

But you can also pass a mutable parameter, and return values via mutation of the object as well:

def func(a):     a.append(1)     a.append(2)     a.append(3)  L=[] func(L) print(L)   # [1,2,3] 
like image 169
Mark Tolonen Avatar answered Sep 21 '22 04:09

Mark Tolonen


You mean like passing by reference?

For Python object the default is to pass by reference. However, I don't think you can change the reference in Python (otherwise it won't affect the original object).

For example:

def addToList(theList):   # yes, the caller's list can be appended     theList.append(3)     theList.append(4)  def addToNewList(theList):   # no, the caller's list cannot be reassigned     theList = list()     theList.append(5)     theList.append(6)  myList = list() myList.append(1) myList.append(2) addToList(myList) print(myList)   # [1, 2, 3, 4] addToNewList(myList) print(myList)   # [1, 2, 3, 4] 
like image 24
helloworld922 Avatar answered Sep 21 '22 04:09

helloworld922