一 函数(function)
文档字符串docstring
可变参数args,*kwargs
匿名函数lambda
高阶函数map, filter, sorted
#!/usr/bin/env python# -*- coding=utf-8 -*-import sysdef func1(*args, **kwargs):"""this function accepts any argumentsargs: positional argumentskwargs: key-word arguments"""print 'args:', argsprint 'kwargs:', kwargsif __name__ == "__main__":help(func1)print '=' * 15func1(1, 2, c=3, d=4)print '=' * 15func1(*[1, 2, 3], **{'c': 4, 'd': 5})print '=' * 15func1(*sys.argv[1:])
#!/usr/bin/env python# -*- coding=utf-8 -*-# lambadaprint '> lambda test'print (lambda x: x * x)(5)print (lambda x, y: x + y)(3, 4)li = [1, 2, 3, 4, 5]# mapprint '> map test'print [str(i) for i in li]print map(str, li)print [i*i for i in li]print map(lambda x: x*x, li)# filterprint '> filter test'print [i for i in li if i % 2]print filter(lambda x: x % 2, li)# sortedli = ['10', '2', '9', '11']print '> sorted test'print sorted(li)print sorted(li, reverse=True)print sorted(li, key=int)li = ['A', 'b', 'C', 'd']print sorted(li)print sorted(li, key=str.upper)print sorted(li, key=lambda x: x.upper())# other: enumerate zipfor i, n in enumerate(range(5)):print i, nl1 = [1, 2, 3]l2 = ['a', 'b', 'c']for a, b in zip(l1, l2):print a, bd = {a: b for a, b in zip(l1, l2)}print ddd = dict(zip(l1, l2))print dd
二 生成器(generator)
#!/usr/bin/env python# -*- coding=utf-8 -*-# 列表推导式a = [i for i in range(3)]print type(a), a# 字典推导式d = {x: x*x for x in range(3)}print type(d), d# 元组推导式?t = (i for i in range(3))print type(t), t# ============= 生成器 =================# nextg = (i for i in range(3))print next(t) # 0print next(t) # 1print next(t) # 2# print next(t) # StopIteration# forg = (i for i in range(3))for each in g:print each# listg = (i for i in range(3))l1 = list(g) # 一次性的print 'l1:', l1l2 = list(g)print 'l2:', l2# yielddef fib(N):a, b = 0, 1while b <= N:yield ba, b = b, a + bf = fib(10)print type(f), ffor each in f:print each
三 类(class)
#!/usr/bin/env python# -*- coding=utf-8 -*-# Basicclass Test(object):"""docstring for class Test ..."""def __init__(self, name='zoro', age=18):self.name = nameself.age = ageprint self.__dict__def say_hello(self):"""docstring for function hello ..."""print 'hello {name}, you are {age} years old.'.format(**self.__dict__)help(Test)a = Test()help(a.say_hello)a.say_hello()# 继承class Test2(Test):"""docstring for Test2 ..."""def __init__(self, like, *args, **kwargs):super(Test2, self).__init__(*args, **kwargs)self.like = likeprint self.__dict__def show_like(self):print self.__dict__print 'I am {name}, and I like {like}'.format(**self.__dict__)# help(Test2)b = Test2(name='luffy', like='meat')b.say_hello()b.show_like()# 类属性, 魔法方法class A(object):member = []def __init__(self, name='zoro'):self.name = nameself.member.append(name)def __str__(self):return 'There are {} members: {}'.format(len(self.member), self.member)__repr__ = __str__a = A()print ab = A('sanji')print b# 装饰器from datetime import datetimeimport dateutil.parserclass A(object):def __init__(self, name='zoro', age=18):self.name = nameself.age = age@propertydef info(self):return 'You are {name}, and you are {age} years old'.format(**self.__dict__)@staticmethoddef show_time(time_str, time_fmt='%Y-%m-%d %H:%M:%S'):print dateutil.parser.parse(time_str).strftime(time_fmt)a = A()print a.infoA.show_time('20180718')
