python – 类中的所有函数都有__enter__和__exit__等价物吗?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 类中的所有函数都有__enter__和__exit__等价物吗?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2434字,纯文字阅读大概需要4分钟。
内容图文
![python – 类中的所有函数都有__enter__和__exit__等价物吗?](/upload/InfoBanner/zyjiaocheng/802/a5c8c238d4ea48afa813d0a72b7d3d5e.jpg)
我在使用数据库(或文件)时发现非常方便的python的一个功能是你可以给一个类的__enter__和__exit__函数.现在通过使用with语句,您可以确保在此块中首先调用__enter__(并且您可以打开数据库或文件),并在完成后调用__exit__(并且可以关闭数据库或文件.
每次调用我的Database类中的函数时,我想打开和关闭一个sqlite事务.我可以在每个函数的开头和结尾处执行它,但是因为必须为每个函数完成该类,我想知道,是否有在每个函数调用之前和之后调用的方法?像单元测试中的SetUp和TearDown一样.
解决方法:
您可以使用饼图装饰器来装饰每个成员函数
@transaction
def insertData(self):
# code
和事务是一个装饰器,你定义用一个前置和后置包装函数.
是的,你必须为每个功能做到这一点.这是一个例子
def transaction(f):
def pre():
print "pre transaction"
def post():
print "post transaction"
def wrapped(*args):
pre()
f(*args)
post()
return wrapped
class Foo(object):
def __init__(self):
print "instantiating"
def doFoo(self):
print "doing foo"
@transaction
def doBar(self, value):
print "doing bar "+str(value)
@transaction
def foofunc():
print "hello"
foofunc()
f=Foo()
f.doFoo()
f.doBar(5)
.
stefanos-imac:python borini$python decorator.py
pre transaction
hello
post transaction
instantiating
doing foo
pre transaction
doing bar 5
post transaction
另一种方法是使用元类,如下所示:
import types
class DecoratedMetaClass(type):
def __new__(meta, classname, bases, classDict):
def pre():
print "pre transaction"
def post():
print "post transaction"
newClassDict={}
for attributeName, attribute in classDict.items():
if type(attribute) == types.FunctionType:
def wrapFunc(f):
def wrapper(*args):
pre()
f(*args)
post()
return wrapper
newAttribute = wrapFunc(attribute)
else:
newAttribute = attribute
newClassDict[attributeName] = newAttribute
return type.__new__(meta, classname, bases, newClassDict)
class MyClass(object):
__metaclass__ = DecoratedMetaClass
def __init__(self):
print "init"
def doBar(self, value):
print "doing bar "+str(value)
def doFoo(self):
print "doing foo"
c = MyClass()
c.doFoo()
c.doBar(4)
这是纯粹的黑魔法,但它的作用
stefanos-imac:python borini$python metaclass.py
pre transaction
init
post transaction
pre transaction
doing foo
post transaction
pre transaction
doing bar 4
post transaction
你通常不想装饰__init__,你可能只想装饰那些带有特殊名称的方法,所以你可能想要替换它们
for attributeName, attribute in classDict.items():
if type(attribute) == types.FunctionType:
喜欢的东西
for attributeName, attribute in classDict.items():
if type(attribute) == types.FunctionType and "trans_" in attributeName[0:6]:
这样,只有trans_whatever的方法才会被转换.
内容总结
以上是互联网集市为您收集整理的python – 类中的所有函数都有__enter__和__exit__等价物吗?全部内容,希望文章能够帮你解决python – 类中的所有函数都有__enter__和__exit__等价物吗?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。