python with..as.. __call__ __enter__ __exit__
2017-03-24 19:14
405 查看
with .. as ..
python 中的with as# coding=utf8 __author__ = 'Administrator' import inspect class Test(object): """ 测试__call__, __exit__, __enter__ 作用: 1.简化代码 2.释放资源 3易于阅读 """ def __init__(self, name): self.name = name def __enter__(self): # 在with后面的表达式取值后的对象中调用 print "func:{}".format(inspect.stack()[0][3]) def __exit__(self, exc_type, exc_val, exc_tb): # 结束后调用 frame_stack = inspect.stack() print "func:{}".format(frame_stack[0][3]) # 返回函数名 print "func:{}".format(inspect.getframeinfo(frame_stack[0][0])) # 返回追踪信息 self.test() def test(self): print "func:{}".format(inspect.stack()[0][3]) if __name__ == "__main__": with Test("ha") as test: print "123"
运行结果
func:__enter__ 123 func:__exit__ func:Traceback(filename='E:/Project/Actneed4/furion/test/test_built_in.py', lineno=21, function='__exit__', code_context=[' print "func:{}".format(inspect.getframeinfo(frame_stack[0][0]))\n'], index=0) func:test
__call__函数如果在类中被实现了,表示此类可以被直接调用(像对象调用方法一样),此时对象与函数的功能类似
例如:
class_obj(arg1, arg2)
补充:inspect 库可以追踪一些信息,在这里用来获取当前函数名(函数内部获取)
函数外部获取函数,可以通过,
getattr("obj", "name", default=None)或是:
obj.__getattribute__("func_name")
相关文章推荐
- python ------------- __enter__(),__exit__(),with
- Python with解析 __enter__()、__exit__() (十五)
- python __enter__ 与 __exit__的作用,以及与 with 语句的关系
- python __enter__ 与 __exit__的作用,以及与 with 语句的关系
- 【Python】上下文管理 with...as...
- Centos4.3安装MySQL-python-1.2.3,出现error: command 'gcc' failed with exit status 1
- [Python]安装PIL出现command 'gcc' failed with exit status 1错误
- 学习Python:with...as的用法
- Python中的with...as语法
- python with...as...用法
- 安装python-MySQLdb 出现error: command 'gcc' failed with exit status 1的解决方法
- python 中关于with...as的用法
- Python的with...as的用法
- 编译python拓展pycurl抛error: command 'gcc' failed with exit status 1
- 安装MySQL-python时发生错误:error: command 'gcc' failed with exit status 1
- python with/as
- MAC安装python模块碰到“error: command 'cc' failed with exit status 1”解决办法
- 安装python模块时出现:error: Setup script exited with error: command 'gcc' failed with exit status 1
- python之raise、assert、with/as环境管理器
- python之with...as