某些语言具有使用C#等参数返回值的功能.我们来看一个例子:
class OutClass
{
static void OutMethod(out int age)
{
age = 26;
}
static void Main()
{
int value;
OutMethod(out value);
// value is now 26
}
}
Run Code Online (Sandbox Code Playgroud)
那么在Python中有什么类似的东西来获取使用参数的值吗?
Mar*_*nen 54
没有理由,因为Python可以返回多个值:
def func():
return 1,2,3
a,b,c = func()
Run Code Online (Sandbox Code Playgroud)
但是你也可以传递一个可变参数,并返回值:
def func(a):
a.append(1)
a.append(2)
a.append(3)
L=[]
func(L)
print(L) # [1,2,3]
Run Code Online (Sandbox Code Playgroud)
你的意思是喜欢通过参考传递?
对于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]
Run Code Online (Sandbox Code Playgroud)