Python语言中的所有参数(参数)均通过引用传递。这意味着,如果您更改函数中参数所指的内容,则更改也将反映在调用函数中。
#!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist.append([1,2,3,4]); print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist
输出结果
在这里,我们维护对传递对象的引用,并将值附加在同一对象中。因此,这将产生以下结果-
Values inside the function: [10, 20, 30, [1, 2, 3, 4]] Values outside the function: [10, 20, 30, [1, 2, 3, 4]]
还有一个示例,其中参数通过引用传递,并且引用在调用的函数内部被覆盖。
#!/usr/bin/python # Function definition is here def changeme( mylist ): "This changes a passed list into this function" mylist = [1,2,3,4]; # This would assig new reference in mylist print "Values inside the function: ", mylist return # Now you can call changeme function mylist = [10,20,30]; changeme( mylist ); print "Values outside the function: ", mylist
输出结果
参数mylist对于函数changeme是本地的。在函数中更改mylist不会影响mylist。该函数什么都不做,最后将产生以下结果-
Values inside the function: [1, 2, 3, 4] Values outside the function: [10, 20, 30]