【发布时间】:2013-10-01 09:51:14
【问题描述】:
我不知道为什么我突然想到了这一点,但是如果我有一个符合上下文管理器的类,它是另一个上下文管理器类的子类,如下所示。我已经展示了__exit__ 调用close() 的“典型”模型。我的问题是:应该 bar.__exit__() 显式调用 super(bar,self).__exit__(args) 还是应该 bar 的 close() 调用 foo 的 close 或???在这种情况下,这里推荐的模型是什么?
class foo(object):
def __enter__(self):
pass
def __exit__(self,*exc_info):
self.close()
return False
def close(self):
pass
class bar(foo):
def __enter__(self):
pass
def __exit__(self,*exc_info):
self.close()
return False
def close(self):
super(bar,self).close() # is this the recommend model?
谢谢。
【问题讨论】:
-
你想让超类的行为生效吗?这取决于您是要替换还是扩展超类行为。
标签: python subclass exit superclass