Python中有没有通过输出参数返回值的方法?
有些编程语言,比如C#,可以通过参数来返回值。我们来看一个例子:
class OutClass
{
static void OutMethod(out int age)
{
age = 26;
}
static void Main()
{
int value;
OutMethod(out value);
// value is now 26
}
}
那么在Python中有没有类似的方式可以通过参数来获取值呢?
6 个回答
4
把一个列表或者类似的东西传进去,然后把返回的结果放到里面。
8
你是说像通过引用传递吗?
在Python中,默认情况下是通过引用传递对象。不过,我觉得在Python里你不能改变这个引用(否则就不会影响到原来的对象)。
举个例子:
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]
87
Python可以返回一个包含多个项目的元组:
def func():
return 1,2,3
a,b,c = func()
但是你也可以传递一个可变的参数,通过改变这个对象的内容来返回值:
def func(a):
a.append(1)
a.append(2)
a.append(3)
L=[]
func(L)
print(L) # [1,2,3]