昨今两天把Python高级编程过了遍,编程语言通用的部分都比较熟悉了,就跳过了。总结下:
1、列表推导
def _treatment(pos,element):
return '%d, %s' %(pos,element)
#列表推导
print([i for i in range(0,10,1) if i%2==0])
seq = ["one","two","three"]
print([_treatment(pos,element) for pos,element in enumerate(seq)])
2、生成器
def fibonacci():
a,b=0,1
while True:
yield b
a,b = b,a+b
#生成器
#当需要一个将返回一个序列或者在循环中执行的函数时,就应该考虑生成器,
#当这些元素将被传递到另一个函数中以进行后续处理时,一次返回一个元素以提高整体性能
fib = fibonacci()
print([fib.__next__() for i in range(10)])
3、生成器表达式
#生成器表达式
print("generator expression")
iter = (x**2 for x in range(10) if x%2==0)
for el in iter:
print(el)
4、迭代器
class MyIterator(object):
def __init__(self,step):
self.step = step
def __next__(self):
if self.step==0:
raise StopIteration
self.step = self.step-1
return self.step
def __iter__(self):
return self
for el in MyIterator(10):
print(el)
5、装饰器
#简单装饰器
def use_logging(func):
def wrapper(*args,**kwargs):
logging.warning("%s is running" %func.__name__)
return func(*args)
return wrapper
@use_logging
def foo():
print("i am foo")
@use_logging
def bar():
print("i am bar")
#带参数的装饰器
def use_logging(level):
def decorator(func):
def wrapper(*args,**kwargs):
if level=="warning":
logging.warning("%s is running" %func.__name__)
return func(*args)
return wrapper
return decorator
@use_logging("warning")
def foo_with_parameters(name='foo'):
print('i am %s' %name)
class Foo(object):
def __init__(self,func):
self.func = func
def __call__(self, *args, **kwargs):
print("class decorator running")
self.func()
print("class decorator ending")
#类装饰器
@Foo
def bar_class():
print("bar")
def main():
bar()
foo_with_parameters()
bar_class()
6、itertools
http://www.wklken.me/posts/2013/08/20/python-extra-itertools.html#itertoolsisliceiterable-stop
这个帖子是基于Python2讲解的,3的话把izip,imap等都省略了
7、协程
引用multitask,可以下载源代码直接import
def client_handler(sock):
with closing(sock):
while(True):
data = (yield multitask.recv(sock,1024))
if not data:
break
print(data)
yield multitask.send(sock,data)
def echo_server(hostname,port):
addrinfo = socket.getaddrinfo(hostname,port,socket.AF_UNSPEC,socket.SOCK_STREAM)
(family,socktype,proto,canonname,sockaddr) = addrinfo[0]
with closing(socket.socket(family,socktype,proto)) as sock:
sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
sock.bind(sockaddr)
sock.listen(5)
while True:
multitask.add(client_handler((yield multitask.accept(sock))[0]))
def coroutine_1():
for i in range(3):
print('c1')
yield i
def coroutine_2():
for i in range(3):
print('c2')
yield i
def main():
# multitask.add(coroutine_1())
# multitask.add(coroutine_2())
#
# multitask.run()
import sys
hostname=None
port = 1111
if len(sys.argv)>1:
hostname = sys.argv[1]
if len(sys.argv)>2:
port = sys.argv[2]
multitask.add(echo_server(hostname,port))
try:
multitask.run()
except KeyboardInterrupt:
pass
return
8、最佳实践
1)应该避免多重继承
2)super的使用必须一致
3)不要混用老式和新式的类
4)调用父类必须检查类层次,调用_mro_查看当前类的结构层次
5)私有变量和函数都在前面加_