转载:
http://blog.chinaunix.net/uid-20937170-id-3275808.html
文章转载自:易百教程 [http:/www.yiibai.com]
以下为我的概括:
1、定义
def a():
print('hello')
无return时,返回none
括号里可以放参数,参数是有 顺序的
2、
调用函数
a()
3、
by value 和by reference
所有 参数 在python 中 都是引用传递, 此处 需对 PYTHON的对象 机制有所了解
试比较下面的不同
如
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
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]]
还有就是参数通过引用传递和引用被覆盖在被调用的函数里面一个例子。
又
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
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
输出
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
解释:
第一个 例子是
mylist 先指向[10,20,30]地址上的值,再在该地址里面添加了新元素,因此地址上的元素变了
第二个例子是
mylist 先指向了[10,20,30],而函数里面的mylist 指向了 [1,2,3,4],两个是不同的mylist,故不变
4、函数参数
4.1基本参数
4.2关键词参数
如
def a(str1,str2):
print(str1,str2)
a(str2='hello',str1='dsp')
即 传入 hello
此时 可无序
4.3默认参数
假设一个默认值,如果不提供的函数调用的参数值的参数。
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name;
print "Age ", age;
return;
printinfo( age=50, name="miki" );
printinfo( name="miki" );
输出:
Name: miki
Age 50
Name: miki
Age 35
4.4
可变长度参数
参数个数 不确定
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print("Output is: ")
print(arg1)
print(vartuple)
for var in vartuple:
print(var)
return;
# Now you can call printinfo function
printinfo( 10 );
printinfo( 70, 60, 50 );
输出
Output is:
10
Output is:
70
60
50
5、匿名函数
lambda
例子
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))
输出
Value of total : 30
Value of total : 40
语法:
lambda [arg1 [,arg2,.....argn]]:expression
6、return
返回值(因为变量有作用域)
全局变量
局部变量