Python 中有没有一种方法可以编写一个除非与 with 语句一起使用否则会出错的类?
# Okay:
with Foo() as f1:
f1.func1()
f1.func2()
# Not okay:
f2 = Foo()
f2.func1()
我可以手动完成:有__enter__
设置一个标志并让所有其他方法检查该标志。但有更好的方法吗?
以下是不太可能的方式的代码:
class Foo(object):
def __init__(self):
self._entered = False
def __enter__(self):
self._entered = True
return self
def _verify_entered(self):
if not self._entered:
raise Exception("Didn't get call to __enter__")
def __exit__(self, typ, val, traceback):
self._verify_entered()
print("In __exit__")
def func1(self):
self._verify_entered()
# do stuff ...
def func2(self):
self._verify_entered()
# do other stuff
从技术上讲,我认为 agf 是正确的,因为您可以使用元类来自动化这些东西。但是,如果我正确理解其背后的基本动机,我会建议采用不同的方式。
假设你有一个Payload
您想要通过上下文管理器保护的类。在这种情况下,您只需创建一个返回它的上下文管理器:
# This should go in a private module.
class Payload(object):
def __init__(self):
print 'payload ctor'
# This should go in the public interface.
class Context(object):
def __init__(self):
# Set up here the parameters.
pass
def __enter__(self):
# Build & return a Payload object
return Payload()
def __exit__(self, exc_type, exc_val, exc_tb):
# Cleanup
pass
with Context() as f:
# f here is a Payload object.
如果你隐藏Payload
在私有模块中,你很好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)