python3 函数

 

转载:

http://blog.chinaunix.net/uid-20937170-id-3275808.html

http://www.yiibai.com/python/python_functions.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 

返回值(因为变量有作用域)


7、变量的作用域 
全局变量
局部变量





















  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值