您的位置:首页 > 编程语言 > Python开发

【python】如何在类方法前添加装饰器

2016-02-03 12:14 776 查看
import traceback

def close_connection():
def _wrapper(func):
def __wrapper(self, *args, **kwargs):
try:
result = func(self, *args, **kwargs)
return result
except Exception, e:
print ('Exception: %s' % traceback.format_exc())
raise e
finally:
self.close()
return __wrapper

return _wrapper

class Caculator(object):

@close_connection()
def chufa(self, x, y):
try:
result = x/y
except Exception, e:
raise e

return result

def close(self):
print "CLOSE !!!"

caculator = Caculator()
result = caculator.chufa(6, 0)
print result


[1] PEP 318 - Decorators for Functions
and Methods

[2] https://docs.python.org/2/library/functions.html#property
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 迭代器 class