python传参数

时间:2022-12-05 19:41:48

Python参数传递采用的肯定是“传对象引用”的方式。这种方式相当于传值和传引用的一种综合。如果函数收到的是一个可变对象(比如字典或者列表)的引用,就能修改对象的原始值--相当于通过“传引用”来传递对象。如果函数收到的是一个不可变对象(比如数字、字符或者元组)的引用,就不能直接修改原始对象--相当于通过“传值'来传递对象。

列表,字典等参数: 传引用,函数中对这些对象做修改,原来的值也会被修改。

int,string, tuple: 传引用,但是结果像传值,函数的修改不会反映到原变量。


#!/usr/bin/python
# -*- coding: utf-8 -*- a = {i: i*i for i in range(10)}
b = 10
c = "hello world!" def pop_list(x):
for i in range(len(x)):
x.pop(i)
print x def decrease(y):
y = y-2
print y def slice(string):
string = string[:2]
print string if __name__ == "__main__":
print "-" * 10 + "original a" + "-" * 10
print a
print "-"*10 + "params in function" + "-"*10
pop_list(a)
print "-" * 10 + "a" + "-" * 10
print a print "-" * 10 + "original b" + "-" * 10
print b
print "-" * 10 + "params in function" + "-" * 10
decrease(b)
print "-" * 10 + "b" + "-" * 10
print b print "-" * 10 + " original c" + "-" * 10
print c
print "-" * 10 + "params in function" + "-" * 10
slice(c)
print "-" * 10 + "c" + "-" * 10
print c

output:

----------original a----------

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

----------params in function----------

{}

----------a----------

{}

----------original b----------

10

----------params in function----------

8

----------b----------

10

---------- original c----------

hello world!

----------params in function----------

he

----------c----------

hello world!

 

ref: http://www.cnblogs.com/loleina/p/5276918.html