Python 学习笔记 9.函数(Function)

 转载自:http://www.xwy2.com/article.asp?id=115

Code
>>>>>> def Foo(a, b= 1, c = 2):
print "a=%s, b=%s, c=%s"%
(a, b ,c)


>>>>>> Foo(0, 0 ,7
)
a
=0, b=0, c=7

>>>>>>
Foo(0, 0)
a
=0, b=0, c=2

>>>>>> Foo(7
)
a
=7, b=1, c=2

>>>>>> Foo(c = 3, a = 4
)
a
=4, b=1, c=3

>>>>>>

Python 支持类似 Object Pascal 那样的全局函数,也就说我们可以用结构化方式写一些小程序。

Code
>>>>>> def Foo(s):
print
s


>>>>>> Foo("Hello Python!"
)
Hello Python!
>>>>>>

Python 函数的参数也采取引用拷贝的方式,也就是说对参数变量赋值,并不会影响外部对象。

Code
>>>>>> def Fun(i):
print
id(i)
i
= 10



>>>>>> a = 100

>>>>>>
id(a)
11229556

>>>>>>
Fun(a)
11229556

>>>>>>
a
100

>>>>>>

Python 还支持类似 C# params 那样的可变参数数组。

Code
>>>>>> def MyFun1(*i):
print
type(i)
for n in i: print
n


>>>>>> MyFun1(1,2,3,4
)
<type 'tuple'>

1

2

3

4


>>>>>> def MyFun2(**
i):
print
type(i)
for(m, n) in
i.items():
print m, "="
, n


>>>>>> MyFun2(a=1, b=2, c=3
)
<type 'dict'>

a
= 1

c
= 3

b
= 2

>>>>>>

Python 提供了一个内置函数 apply() 来简化函数调用。

Code
>>>>>> def Fun(a, b, c):
print
a, b, c


>>>>>> a = ("l", "M", "n"
)
>>>>>> Fun(a[0], a[1], a[2
])
l M n
>>>>>>
apply(Fun, a)
l M n
>>>>>>

Lambda 是个非常实用的语法,可以写出更简练的代码。

Code
>>>>>> def Do(fun, nums):
for i in
range(len(nums)):
nums[i]
=
fun(nums[i])
print
nums


>>>>>> def
Fun(i):
return i*10


>>>>>> Do(Fun, [1, 2, 3
])
[
10, 20, 30
]
>>>>>> Do(lambda i: i*10, [1, 2, 3]) # 使用 lambda

[10, 20, 30]
>>>>>>

还有一点比较有意思,由于 Python 函数无需定义返回值,因此我们可以很容易地返回多个结果。这种方式也可以从一定程度上替代 ref/out 的功能。

Code
>>>>>> def Fun():
return 1, 2, 3


>>>>>> a =
Fun()
>>>>>>
type(a)
<type 'tuple'>

>>>>>>
a
(
1, 2, 3)(1, 2, 3
)
>>>>>>

当然,函数参数和原变量同时指向同一对象,我们是可以改变该对象成员的。

Code
>>>>>> class Data:
def __init__
(self):
self.i
= 10



>>>>>> def
Fun(d):
d.i
= 100



>>>>>> d =
Data()
>>>>>>
d.i
10

>>>>>>
Fun(d)
>>>>>>
d.i
100

>>>>>>

我们可以使用 global 关键词来实现类似 C# ref/out 的功能。

Code
>>>>>> def Foo():
global
i
i
= 100



>>>>>> i = 10

>>>>>>
Foo()
>>>>>>
i
100

>>>>>>

Python 不支持方法重载,但支持缺省参数和一些特殊的调用方式。

原文地址:https://www.cnblogs.com/sislcb/p/1284830.html