一 函数(function)

  1. 文档字符串docstring

  2. 可变参数args,*kwargs

  3. 匿名函数lambda

  4. 高阶函数map, filter, sorted

  1. #!/usr/bin/env python
  2. # -*- coding=utf-8 -*-
  3. import sys
  4. def func1(*args, **kwargs):
  5. """
  6. this function accepts any arguments
  7. args: positional arguments
  8. kwargs: key-word arguments
  9. """
  10. print 'args:', args
  11. print 'kwargs:', kwargs
  12. if __name__ == "__main__":
  13. help(func1)
  14. print '=' * 15
  15. func1(1, 2, c=3, d=4)
  16. print '=' * 15
  17. func1(*[1, 2, 3], **{'c': 4, 'd': 5})
  18. print '=' * 15
  19. func1(*sys.argv[1:])
  1. #!/usr/bin/env python
  2. # -*- coding=utf-8 -*-
  3. # lambada
  4. print '> lambda test'
  5. print (lambda x: x * x)(5)
  6. print (lambda x, y: x + y)(3, 4)
  7. li = [1, 2, 3, 4, 5]
  8. # map
  9. print '> map test'
  10. print [str(i) for i in li]
  11. print map(str, li)
  12. print [i*i for i in li]
  13. print map(lambda x: x*x, li)
  14. # filter
  15. print '> filter test'
  16. print [i for i in li if i % 2]
  17. print filter(lambda x: x % 2, li)
  18. # sorted
  19. li = ['10', '2', '9', '11']
  20. print '> sorted test'
  21. print sorted(li)
  22. print sorted(li, reverse=True)
  23. print sorted(li, key=int)
  24. li = ['A', 'b', 'C', 'd']
  25. print sorted(li)
  26. print sorted(li, key=str.upper)
  27. print sorted(li, key=lambda x: x.upper())
  28. # other: enumerate zip
  29. for i, n in enumerate(range(5)):
  30. print i, n
  31. l1 = [1, 2, 3]
  32. l2 = ['a', 'b', 'c']
  33. for a, b in zip(l1, l2):
  34. print a, b
  35. d = {a: b for a, b in zip(l1, l2)}
  36. print d
  37. dd = dict(zip(l1, l2))
  38. print dd

二 生成器(generator)

  1. #!/usr/bin/env python
  2. # -*- coding=utf-8 -*-
  3. # 列表推导式
  4. a = [i for i in range(3)]
  5. print type(a), a
  6. # 字典推导式
  7. d = {x: x*x for x in range(3)}
  8. print type(d), d
  9. # 元组推导式?
  10. t = (i for i in range(3))
  11. print type(t), t
  12. # ============= 生成器 =================
  13. # next
  14. g = (i for i in range(3))
  15. print next(t) # 0
  16. print next(t) # 1
  17. print next(t) # 2
  18. # print next(t) # StopIteration
  19. # for
  20. g = (i for i in range(3))
  21. for each in g:
  22. print each
  23. # list
  24. g = (i for i in range(3))
  25. l1 = list(g) # 一次性的
  26. print 'l1:', l1
  27. l2 = list(g)
  28. print 'l2:', l2
  29. # yield
  30. def fib(N):
  31. a, b = 0, 1
  32. while b <= N:
  33. yield b
  34. a, b = b, a + b
  35. f = fib(10)
  36. print type(f), f
  37. for each in f:
  38. print each

三 类(class)

  1. #!/usr/bin/env python
  2. # -*- coding=utf-8 -*-
  3. # Basic
  4. class Test(object):
  5. """
  6. docstring for class Test ...
  7. """
  8. def __init__(self, name='zoro', age=18):
  9. self.name = name
  10. self.age = age
  11. print self.__dict__
  12. def say_hello(self):
  13. """
  14. docstring for function hello ...
  15. """
  16. print 'hello {name}, you are {age} years old.'.format(**self.__dict__)
  17. help(Test)
  18. a = Test()
  19. help(a.say_hello)
  20. a.say_hello()
  21. # 继承
  22. class Test2(Test):
  23. """
  24. docstring for Test2 ...
  25. """
  26. def __init__(self, like, *args, **kwargs):
  27. super(Test2, self).__init__(*args, **kwargs)
  28. self.like = like
  29. print self.__dict__
  30. def show_like(self):
  31. print self.__dict__
  32. print 'I am {name}, and I like {like}'.format(**self.__dict__)
  33. # help(Test2)
  34. b = Test2(name='luffy', like='meat')
  35. b.say_hello()
  36. b.show_like()
  37. # 类属性, 魔法方法
  38. class A(object):
  39. member = []
  40. def __init__(self, name='zoro'):
  41. self.name = name
  42. self.member.append(name)
  43. def __str__(self):
  44. return 'There are {} members: {}'.format(len(self.member), self.member)
  45. __repr__ = __str__
  46. a = A()
  47. print a
  48. b = A('sanji')
  49. print b
  50. # 装饰器
  51. from datetime import datetime
  52. import dateutil.parser
  53. class A(object):
  54. def __init__(self, name='zoro', age=18):
  55. self.name = name
  56. self.age = age
  57. @property
  58. def info(self):
  59. return 'You are {name}, and you are {age} years old'.format(**self.__dict__)
  60. @staticmethod
  61. def show_time(time_str, time_fmt='%Y-%m-%d %H:%M:%S'):
  62. print dateutil.parser.parse(time_str).strftime(time_fmt)
  63. a = A()
  64. print a.info
  65. A.show_time('20180718')