[Python 学习笔记] 8: Function



  Python 支持类似 Object Pascal 那样全局也就说我们可以用结构化方式写些小

>>> def test(s):
  pr s
>>> test("Hello, World!")
Hello, World!


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

>>> def fun(i):
  pr id(i)
  i = 10
  
>>> a = 100
>>> id(a)
11229364
>>> fun(a)
11229364
>>> a
100


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

>>>  Data:
  def __init__(self):
    self.i = 0
    
>>> def fun(d):
  d.i = 100
  
>>> d = Data
>>> d.i
0
>>> fun(d)
>>> d.i
100


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

>>> def test:
  global i
  i = 100
  
>>> i = 10
>>> test
>>> i
100


  Python 不支持思路方法重载但支持缺省参数和些特殊方式

>>> def test(a, b = 1, c = 2):
  pr "a=%s, b=%s, c=%s" % (a, b, c)
  
>>> test(0, 1, 2)
a=0, b=1, c=2
>>> test(0, 1)
a=0, b=1, c=2
>>> test(0)
a=0, b=1, c=2
>>> test(c=3, a=2)
a=2, b=1, c=3


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

>>> def fun1(*i):
  pr type(i)
  for n in i: pr n
  
>>> fun1(1, 2, 3, 4)
<type 'tuple'>
1
2
3
4
>>> def fun2(**d):
  pr type(d)
  for (k, v) in d.items:
    pr k, "=", v
    
>>> fun2(a=1, b=2, c=3)
<type 'dict'>
a = 1
c = 3
b = 2


  Python 提供了个内置 apply 来简化

>>> a = (1, 2, 3)
>>> def fun(a, b, c):
  pr a
  pr b
  pr c
>>> fun(a[0], a[1], a[2])
1
2
3
>>> apply(fun, a)
1
2
3


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

>>> def do(fun, nums):
  for i in range(len(nums)):
    nums[i] = fun(nums[i])
  pr nums
>>> def fun(i):
   i + 1
>>> do(fun, [1, 2, 3])
[2, 3, 4]
>>> do(lambda i: i + 1, [1, 2, 3])
[2, 3, 4]
>>> 


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

>>> def fun:
   1, 2, 3
>>> a = fun
>>> type(a)
<type 'tuple'>
>>> a[2]
3


Tags: 

延伸阅读

最新评论

发表评论