【发布时间】:2016-03-08 06:46:22
【问题描述】:
我应该如何正确嵌套与with 相关的类行为(例如在派生或实例化时)?
这对我有用,但我想知道是否有专门的方法来做到这一点:
class class_a:
def __init__(self):
print('class_a::__init__')
def __enter__(self):
print('class_a::__enter__')
return self
def __exit__(self, type, exit, tb):
print('class_a::__exit__')
class class_b(class_a):
def __init__(self):
class_a.__init__(self)
print('class_b::__init__')
def __enter__(self):
class_a.__enter__(self)
print('class_b::__enter__')
return self
def __exit__(self, type, exit, tb):
class_a.__exit__(self, type, exit, tb)
print('class_b::__exit__', type, exit, tb)
with class_b():
print('ready')
try:
signal.pause()
except:
pass
一种不同的方法是像这样实现class_b:
class class_b:
def __init__(self):
self._class_a_inst = class_a()
print('class_b::__init__')
def __enter__(self):
self._class_a_inst.__enter__()
print('class_b::__enter__')
return self
def __exit__(self, type, exit, tb):
self._class_a_inst.__exit__(type, exit, tb)
print('class_b::__exit__', type, exit, tb)
__enter__() / __exit__() 的行为有什么不同吗?
【问题讨论】:
-
我不知道有任何实用程序。你的代码有一个微妙的错误:你不能吞下
class_a.__exit__的返回值。 (决定__exit__何时返回 true/false 很重要;我无法给出更具体的建议。) -
在第二个版本中,您有两个独立的
class_a实例,一个是派生的,一个是委托的。所以这不是你真正想要的。第一个例子在我看来还可以。 -
你当然是对的,但从
class_a派生只是一个复制/粘贴问题。 -
这仍然没有意义,您的问题是“我应该如何正确派生类”
-
@zwol:我的直觉是
class_b::__exit__应该在class_a::__exit__的情况下返回true,并且如果它出于自身原因吞下异常。但你是对的,这需要逐案考虑。
标签: python derived-class with-statement