python查看类信息 对象比较 字符串编解码 生成器 装饰器 异常处理 with-as作用
- 2015-04-11 23:08:00
- admin
- 原创 3218
一、python查看类信息
查看基类:
import inspect
mro_list = inspect.getmro(asyncio.Task)
for cls in mro_list:
print(cls.__name__)
查看成员:
import inspect
members = inspect.getmembers(asyncio.Future)
for member in members:
print(member)
二、python对象比较
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def key(self):
return self.name
def __cmp__(self, other):
return cmp(self.name, other.name)
def __str__(self):
return '%s=%d' %(self.name, self.age)
if __name__ == '__main__':
persons = []
persons.append(Person('allen', 20))
persons.append(Person('bob', 20))
persons.append(Person('candy', 20))
persons.sort()
for item in persons: print item
persons.sort(cmp=lambda x,y:cmp(x.name,y.name), reverse=True)
for item in persons: print item
persons.sort(key=Person.key, cmp=lambda x,y:cmp(x.lower(),y.lower()), reverse=True)
for item in persons: print item
三、修改默认编码
方法1:
设置环境变量PYTHONIOENCODING
方法2:
# -*- coding: utf-8 -*-
方法3:
stdi,stdo,stde=sys.stdin,sys.stdout,sys.stderr
reload(sys)
sys.stdin,sys.stdout,sys.stderr=stdi,stdo,stde
sys.setdefaultencoding('UTF-8')
四、字符串编解码
1、decode将其他编码的字符串转换成unicode编码,str.decode('gb2312')将gb2312编码的字符串转换成unicode编码;
2、encode将unicode编码转换成其他编码的字符串,str.encode('gb2312')将unicode编码的字符串转换成gb2312编码;
输出GBK编码中文示例:
# -*- coding: utf-8 -*-
name = '中国'
name = name.decode('UTF-8').encode('GBK')
print name
五、生成器
1、生成器generator,迭代器iterator,生成器是一种特殊的迭代器;
2、yield操作把函数变成一个生成器,yield执行一次返回一次数据;
3、生成器能够保存函数的执行位置,函数的局部变量;
4、每次迭代时从上次执行的位置继续执行;
5、获取数据通过next(),获取不到数据抛出异常StopIteration;
六、装饰器
1、英文帮助:https://book.pythontips.com/en/latest/decorators.html
2、中文帮助:https://eastlakeside.gitbook.io/interpy-zh/decorators
3、python函数也是一种对象,函数中可以定义函数;
4、函数参数可以是函数,函数返回值可以是函数;
5、func=decorator(originfunc),originfunc原函数,decorator装饰函数,func结果函数;
6、@decorator简化生成装饰函数,@functools.wraps(orignfunc)修改结果函数的名字和注释;
7、装饰器可以在不修改原有函数的情况下,给函数增加新的功能,比如验证权限、记录日志;
七、异常处理
1、异常使用帮助:https://www.w3schools.com/python/python_try_except.asp
2、异常组改进提案:https://peps.python.org/pep-0654
3、except用于处理异常,参数是一个异常;
4、except*用于处理异常组,参数是一个异常组;
5、except*参数异常组包含指定异常类型的一个或多个实例;
6、except和except*不能混合使用,要么全都是except,要么全都是excpet*;
7、异常只能命中一个except,异常组可以命中多个except*,直到异常组所有异常被处理;
8、继承关系:ExceptionGroup -> BaseExceptionGroup -> Exception -> BaseException -> object
推荐第一种异常抛出方式:
raise Exception('password incorrect')
raise Exception,'password incorrect'
raise Exception,('password incorrect')
异常处理:
try:
pass
except Exception as e:
print e
异常组处理:
try:
raise ExceptionGroup(
"error messages",
[ValueError("Invalid value"), TypeError("Wrong type")]
)
except* ValueError as eg:
print(f"Handled ValueError: {eg.exceptions}")
except* TypeError as eg:
print(f"Handled TypeError: {eg.exceptions}")
八、with-as作用
1、同步场景:自动调用对象的__enter__和__exit__方法,用于对象自动初始化和自动清理;
2、异步场景:自动调用对象的__aenter__和__aexit__方法,用于对象自动初始化和自动清理;
with open("/tmp/foo.txt") as myfile:
data = myfile.read()