Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1785215
  • 博文数量: 276
  • 博客积分: 1574
  • 博客等级: 上尉
  • 技术积分: 2894
  • 用 户 组: 普通用户
  • 注册时间: 2010-05-26 23:23
个人简介

生活的美妙在于,不知道一下秒是惊艳还是伤神,时光流转,珍惜现在的拥有的时光

文章分类

全部博文(276)

文章存档

2017年(17)

2016年(131)

2015年(63)

2013年(2)

2012年(32)

2011年(31)

分类: Python/Ruby

2016-02-25 15:04:30

python学习手册19 函数的高级话题

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. #-*- coding:utf8-*-
  3. '''
  4. 函数设计概念
  5.     有针对性的函数-聚合性
  6.     函数如何通信-耦合性
  7.         耦合性:对于输入使用参数并且对于输出使用return语句。
  8.         耦合性:只有真正必要的情况下使用全局变量。
  9.         耦合性:不要改变可变类型的参数,除非调用者希望这样做。
  10.         聚合性:每个函数都应该有一个单一的、统一的目标。
  11.         大小:每个函数都应该相对较小。
  12.         耦合:避免直接改变在另一个模块文件中的变量。
  13. 递归函数
  14.     直接或间接地调用自身以进行循环的函数。
  15.         它在python中相对少见,它是一项应该了解的有用技术,因为它允许遍历拥有任意的,不可预知的形状的结构。
  16. 函数对象:属性和注解
  17.     函数全部存储在内存中,可以跨程序自由地传递和间接调用。也支持与调用无关的操作--属性存储和注解。
  18.     函数可以由一个函数表达式后面的括号中的列表参数调用。
  19.     我们可以自由的把函数对象赋值给其他的名称并且勇冠任何引用调用它。

  20. '''
  21. #定制求和函数
  22. def mysum(L):
  23.     print(L)
  24.     if not L:
  25.         return 0
  26.     else:
  27.         return L[0] + mysum(L[1:])
  28. print(mysum([5,6,7,8,9,10])) #45

  29. def mysum2(T):
  30.     return T[0] if len(T) == 1 else T[0] + mysum2(T[1:])
  31. print(mysum2(['t','a','l','e','n']))
  32. print(mysum2(['ad','vs','ok']))
  33. #def mysum3(C):
  34. # first, *rest = C
  35. # return first if not rest else first + mysum3(rest)
  36. #print(mysum3(['t','a','l','e','n']))
  37. #print(mysum3(['ad','vs','ok']))

  38. #隐性递归
  39. def mysum4(L):
  40.     if len(L) == 0:
  41.         return 0
  42.     else:
  43.         return nonemputy(L)
  44. def nonemputy(L):
  45.     return L[0] + mysum4(L[1:])

  46. print(mysum4([1.1,2.2,3.3]))

  47. #循环语句VS递归,python循环会再自然一些,迭代也比递归在内存空间和执行时间方面效率高一些。
  48. L=[1,2,3,4,5]
  49. sum =0
  50. while L:
  51.     sum += L[0]
  52.     L=L[1:]
  53. print(sum)

  54. L=[1,2,3,4,5,6]
  55. sum=0
  56. for x in L:
  57.     sum +=x
  58. print(sum)

  59. #处理任意结构
  60. L=[1,2,[3,4,[5,6],7,8],9]
  61. M=[1,[2,[3,[4,[5]]]]]
  62. def sumtree(L):
  63.     tot=0
  64.     for x in L:
  65.         if isinstance(x,list):
  66.             tot += sumtree(x)
  67.         else:
  68.             tot += x
  69.     return tot
  70. print(sumtree(L))
  71. print(sumtree(M))
  72. #函数间接调用
  73. def echo(message):
  74.     print(message)
  75. echo('直接调用')
  76. x=echo
  77. x('赋值调用')
  78. def indirect(func,arg):
  79.     func(arg)
  80. indirect(echo,'作为参数调用')
  81. #python复合类型
  82. T=[(echo,'spam!'),(echo,'ham!')]
  83. for (func,arg) in T:
  84.     func(arg)
  85. #函数内省
  86. print(indirect.__name__)
  87. print(dir(indirect))
  88. print(dir(indirect.__code__))
  89. print(indirect.__code__.co_argcount)
  90. print(indirect.__code__.co_varnames)

  91. #函数属性 用户自定义附加
  92. # 属性与对象相关而不是与作用域相关,但是直接效果是类似。
  93. indirect.count=100
  94. print(indirect.count) #100
  95. print(dir(indirect)) #包含有count

  96. #python3.0新功能
  97. #函数注解
  98.     #函数注解编写在def头部行,注解只对def有效,对lambda无效。
  99.         #对于参数,它们出现在紧随参数名之后的冒号之后;
  100.         #对于返回值,它们编写于紧跟在参数列表之后的一个->之后。
  101.         #注解收集到__annotations__
  102. #def funcA(a:'spam',b:(1,10)=10,c:float=5) -> int:
  103. # return a+b+c
  104. #print(func(1,2,3)) #6
  105. #print(funcA.__annotations__) #{'c': <class 'float'>, 'return': <class 'int'>, 'a': 'spam', 'b': (1, 10)}
  106. #注解出现在默认值之前,如c:float=5
  107. #特别注意:函数一个参数如果有一个有默认值,则其后面的参数必须带有默认值否则会报SyntaxError: non-default argument follows default argument


  108. #匿名函数:lambda 函数对象的表达式形式,返回一个函数对象,这个函数没有函数名。更简洁短小。
  109. #lambda表达式:
  110.     #lambda argument1,argument2,argument3,...,argumentN :expression using arguments
  111.     #1.lambda是一个表达式,而不是一个语句
  112.     #2.lambda的主体是一个单个的表达式,而不是一个代码块。
  113.         #lambda是为编写简单函数而设计的,而def用来处理更大的任务。

  114. def knights():
  115.     title = 'Sir'
  116.     action = (lambda x : title + ' ' + x)
  117.     return action
  118. act=knights()
  119. print(act('talen'))

  120. #lambda通常用来编写跳转表(jump table),也就是行为的列表或字典,能够按需执行相应的动作。
  121. L=[
  122.     lambda x: x ** 2,
  123.     lambda x: x ** 3,
  124.     lambda x: x ** 4

  125. ]
  126. for f in L:
  127.     print(f(2))
  128. print(L[0](3))

  129. #当需要把小段的可执行代码编写进def语句从语法上不编写进的地方时,lambda表达式做为def的一种速写来说是最有用的。
  130. key='own'
  131. print({
  132.     'talen':lambda x :2 +x ,
  133.     'own':lambda x : 2 * x ,
  134.     'one':lambda x : 2 ** x ,
  135.  }[key](3))

  136. lower=lambda x,y:x if x<y else y
  137. print(lower('cc','aa'))
  138. print(lower('cc','dd'))

  139. #简洁优于复杂
  140. #嵌套lambda和作用域
  141.     #lambda可以获取嵌套函数作用域的变量名。
  142.     #lambda可以获取任意上层lambda的变量名。
  143.     #出于可读性的要求,尽量避免使用嵌套的lambda。
  144. #在序列中映射函数:map
  145.     #map函数会对一个序列对象中的每一个元素应用被传入的函数,并且返回一个包含了所有函数调用结果的一个列表。
  146.     #它虽不太常用,但运行速度比列表解析要快。
  147. counters=[1,2,3,4,5]
  148. def func(x):
  149.     return x + 100
  150. print(map(func,counters)) #对counters列表中的每一个元素执行func函数操作。
  151. #由于map期待传入一个函数,这恰好是lambda经常出现的地方。
  152. print(map((lambda x : x + 10),counters))
  153. #也可以自己写一个map函数
  154. def mymap(func,seq):
  155.     res=[]
  156.     for x in seq:
  157.         res.append(func(x))
  158.     return res
  159. print(mymap(func,counters))
  160. print(mymap(func,[100,200,300,400]))

  161. print(pow(2,3))
  162. print(map(pow,[1,2,3],[2,3,4]))#将后面2个列表中的元素一一对应给pow函数。

  163. #函数式编程工具:filter和reduce
  164.     #函数式编程就是对序列应用一些函数的工具。
  165. print(list(range(-10,10)))
  166. print(list(filter((lambda x :x > 2),range(-10,10))))#对一个序列执行过滤大于2的元素并列表化。

  167. from functools import reduce
  168. print(reduce((lambda x,y:x+y),[1,2,3,4]))#reduce调用,计算了列表中的所有元素和并返回一个值

  169. #等价自写
  170. def myreduce(func,seq):
  171.     res=seq[0]
  172.     for next in seq[1:]:
  173.         res = func(res,next)
  174.     return res
  175. print(myreduce((lambda x,y: x +y),[1,2,3,4]))

结果

点击(此处)折叠或打开

  1. /usr/bin/python2.7 /home/talen/PycharmProjects/untitled/t19.py
  2. [5, 6, 7, 8, 9, 10]
  3. [6, 7, 8, 9, 10]
  4. [7, 8, 9, 10]
  5. [8, 9, 10]
  6. [9, 10]
  7. [10]
  8. []
  9. 45
  10. talen
  11. advsok
  12. 6.6
  13. 15
  14. 21
  15. 45
  16. 15
  17. 直接调用
  18. 赋值调用
  19. 作为参数调用


  20. indirect
  21. ['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
  22. ['__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']
  23. 2
  24. ('func', 'arg')
  25. 100
  26. ['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
  27. Sir talen
  28. 4
  29. 8
  30. 16
  31. 9
  32. 6
  33. aa
  34. cc
  35. [101, 102, 103, 104, 105]
  36. [11, 12, 13, 14, 15]
  37. [101, 102, 103, 104, 105]
  38. [200, 300, 400, 500]
  39. 8
  40. [1, 8, 81]
  41. [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  42. [3, 4, 5, 6, 7, 8, 9]
  43. 10
  44. 10

  45. Process finished with exit code 0

阅读(1014) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~