#!/usr/bin/env python
# -*- coding: utf-8 -*-
from base import APIBase
from client import Client
from decorator import interface, export, stream
from server import Server
from storage import Storage
from util import (LogFormatter, disable_logging_to_stderr,
enable_logging_to_kids, info)
__all__ = ['APIBase', 'Client', 'LogFormatter', 'Server',
'Storage', 'disable_logging_to_stderr', 'enable_logging_to_kids',
'export', 'info', 'interface', 'stream']
# 常见with使用场景
with open("test.txt", "r") as my_file: # 注意, 是__enter__()方法的返回值赋值给了my_file,
for line in my_file:
print line
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class MyWith(object):
def __init__(self):
print "__init__ method"
def __enter__(self):
print "__enter__ method"
return self # 返回对象给as后的变量
def __exit__(self, exc_type, exc_value, exc_traceback):
print "__exit__ method"
if exc_traceback is None:
print "Exited without Exception"
return True
else:
print "Exited with Exception"
return False
def test_with():
with MyWith() as my_with:
print "running my_with"
print "------分割线-----"
with MyWith() as my_with:
print "running before Exception"
raise Exception
print "running after Exception"
if __name__ == '__main__':
test_with()
__init__ method __enter__ method running my_with __exit__ method Exited without Exception ------分割线----- __init__ method __enter__ method running before Exception __exit__ method Exited with Exception Traceback (most recent call last): File "bin/python", line 34, in <module> exec(compile(__file__f.read(), __file__, "exec")) File "test_with.py", line 33, in <module> test_with() File "test_with.py", line 28, in test_with raise Exception Exception
#!/usr/bin/env python # -*- coding: utf-8 -*- lst = [1, 2, 3, 4, 5, 6] # 所有奇数都会返回True, 偶数会返回False被过滤掉 print filter(lambda x: x % 2 != 0, lst) #输出结果 [1, 3, 5]
lst = [1, 2, 3] new_lst = lst[0] if lst is not None else None print new_lst # 打印结果 1
# 单例装饰器
def singleton(cls):
instances = dict() # 初始为空
def _singleton(*args, **kwargs):
if cls not in instances: #如果不存在, 则创建并放入字典
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return _singleton
@singleton
class Test(object):
pass
if __name__ == '__main__':
t1 = Test()
t2 = Test()
# 两者具有相同的地址
print t1, t2
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class A(object):
# 普通成员函数
def foo(self, x):
print "executing foo(%s, %s)" % (self, x)
@classmethod # 使用classmethod进行装饰
def class_foo(cls, x):
print "executing class_foo(%s, %s)" % (cls, x)
@staticmethod # 使用staticmethod进行装饰
def static_foo(x):
print "executing static_foo(%s)" % x
def test_three_method():
obj = A()
# 直接调用噗通的成员方法
obj.foo("para") # 此处obj对象作为成员函数的隐式参数, 就是self
obj.class_foo("para") # 此处类作为隐式参数被传入, 就是cls
A.class_foo("para") #更直接的类方法调用
obj.static_foo("para") # 静态方法并没有任何隐式参数, 但是要通过对象或者类进行调用
A.static_foo("para")
if __name__ == '__main__':
test_three_method()
# 函数输出
executing foo(<__main__.A object at 0x100ba4e10>, para)
executing class_foo(<class '__main__.A'>, para)
executing class_foo(<class '__main__.A'>, para)
executing static_foo(para)
executing static_foo(para)
#python内建函数 property(fget=None, fset=None, fdel=None, doc=None)
class Student(object):
@property #相当于property.getter(score) 或者property(score)
def score(self):
return self._score
@score.setter #相当于score = property.setter(score)
def score(self, value):
if not isinstance(value, int):
raise ValueError('score must be an integer!')
if value < 0 or value > 100:
raise ValueError('score must between 0 ~ 100!')
self._score = value
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class TestIter(object):
def __init__(self):
self.lst = [1, 2, 3, 4, 5]
def read(self):
for ele in xrange(len(self.lst)):
yield ele
def __iter__(self):
return self.read()
def __str__(self):
return ','.join(map(str, self.lst))
__repr__ = __str__
def test_iter():
obj = TestIter()
for num in obj:
print num
print obj
if __name__ == '__main__':
test_iter()
def partial(func, *part_args):
def wrapper(*extra_args):
args = list(part_args)
args.extend(extra_args)
return func(*args)
return wrapper
#!/usr/bin/env python # -*- coding: utf-8 -*- from functools import partial def sum(a, b): return a + b def test_partial(): fun = partial(sum, 2) # 事先绑定一个参数, fun成为一个只需要一个参数的可调用变量 print fun(3) # 实现执行的即是sum(2, 3) if __name__ == '__main__': test_partial() # 执行结果 5
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def test_first():
return 3
def test_second(num):
return num
action = { # 可以看做是一个sandbox
"para": 5,
"test_first" : test_first,
"test_second": test_second
}
def test_eavl():
condition = "para == 5 and test_second(test_first) > 5"
res = eval(condition, action) # 解释condition并根据action对应的动作执行
print res
if __name__ == '_
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def test_first():
print "hello"
def test_second():
test_first()
print "second"
def test_third():
print "third"
action = {
"test_second": test_second,
"test_third": test_third
}
def test_exec():
exec "test_second" in action
if __name__ == '__main__':
test_exec() # 无法看到执行结果
# 使用范例
class TestGetAttr(object):
test = "test attribute"
def say(self):
print "test method"
def test_getattr():
my_test = TestGetAttr()
try:
print getattr(my_test, "test")
except AttributeError:
print "Attribute Error!"
try:
getattr(my_test, "say")()
except AttributeError: # 没有该属性, 且没有指定返回值的情况下
print "Method Error!"
if __name__ == '__main__':
test_getattr()
# 输出结果
test attribute
test method
def process_command_line(argv):
"""
Return a 2-tuple: (settings object, args list).
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
if argv is None:
argv = sys.argv[1:]
# initialize the parser object:
parser = optparse.OptionParser(
formatter=optparse.TitledHelpFormatter(width=78),
add_help_option=None)
# define options here:
parser.add_option( # customized description; put --help last
'-h', '--help', action='help',
help='Show this help message and exit.')
settings, args = parser.parse_args(argv)
# check number of arguments, verify values, etc.:
if args:
parser.error('program takes no command-line arguments; '
'"%s" ignored.' % (args,))
# further process settings & args if necessary
return settings, args
def main(argv=None):
settings, args = process_command_line(argv)
# application code here, like:
# run(settings, args)
return 0 # success
if __name__ == '__main__':
status = main()
sys.exit(status)
# 从csv中读取文件, 基本和传统文件读取类似
import csv
with open('data.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
# 向csv文件写入
import csv
with open( 'data.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerow(['name', 'address', 'age']) # 单行写入
data = [
( 'xiaoming ','china','10'),
( 'Lily', 'USA', '12')]
writer.writerows(data) # 多行写入
>>> name = "andrew"
>>> "my name is {name}".format(name=name)
'my name is andrew'
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2026 源码网商城 (www.ymwmall.com) 版权所有