一 函数(function)
文档字符串docstring
可变参数args,*kwargs
匿名函数lambda
高阶函数map, filter, sorted
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import sys
def func1(*args, **kwargs):
"""
this function accepts any arguments
args: positional arguments
kwargs: key-word arguments
"""
print 'args:', args
print 'kwargs:', kwargs
if __name__ == "__main__":
help(func1)
print '=' * 15
func1(1, 2, c=3, d=4)
print '=' * 15
func1(*[1, 2, 3], **{'c': 4, 'd': 5})
print '=' * 15
func1(*sys.argv[1:])
#!/usr/bin/env python
# -*- coding=utf-8 -*-
# lambada
print '> lambda test'
print (lambda x: x * x)(5)
print (lambda x, y: x + y)(3, 4)
li = [1, 2, 3, 4, 5]
# map
print '> 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)
# filter
print '> filter test'
print [i for i in li if i % 2]
print filter(lambda x: x % 2, li)
# sorted
li = ['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 zip
for i, n in enumerate(range(5)):
print i, n
l1 = [1, 2, 3]
l2 = ['a', 'b', 'c']
for a, b in zip(l1, l2):
print a, b
d = {a: b for a, b in zip(l1, l2)}
print d
dd = 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
# ============= 生成器 =================
# next
g = (i for i in range(3))
print next(t) # 0
print next(t) # 1
print next(t) # 2
# print next(t) # StopIteration
# for
g = (i for i in range(3))
for each in g:
print each
# list
g = (i for i in range(3))
l1 = list(g) # 一次性的
print 'l1:', l1
l2 = list(g)
print 'l2:', l2
# yield
def fib(N):
a, b = 0, 1
while b <= N:
yield b
a, b = b, a + b
f = fib(10)
print type(f), f
for each in f:
print each
三 类(class)
#!/usr/bin/env python
# -*- coding=utf-8 -*-
# Basic
class Test(object):
"""
docstring for class Test ...
"""
def __init__(self, name='zoro', age=18):
self.name = name
self.age = age
print 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 = like
print 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 = name
self.member.append(name)
def __str__(self):
return 'There are {} members: {}'.format(len(self.member), self.member)
__repr__ = __str__
a = A()
print a
b = A('sanji')
print b
# 装饰器
from datetime import datetime
import dateutil.parser
class A(object):
def __init__(self, name='zoro', age=18):
self.name = name
self.age = age
@property
def info(self):
return 'You are {name}, and you are {age} years old'.format(**self.__dict__)
@staticmethod
def 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.info
A.show_time('20180718')