我正在试验 Python 的with
语句,我发现在下面的代码清单中,我的__init__
方法被调用了两次,而我的__exit__
方法被调用了一次。这大概意味着如果这段代码做了任何有用的事情,就会发生资源泄漏。
class MyResource:
def __enter__(self):
print 'Entering MyResource'
return MyResource()
def __exit__(self, exc_type, exc_value, traceback):
print 'Cleaning up MyResource'
def __init__(self):
print 'Constructing MyResource'
def some_function(self):
print 'Some function'
def main():
with MyResource() as r:
r.some_function()
if __name__=='__main__':
main()
这是程序的输出:
Constructing MyResource
Entering MyResource
Constructing MyResource
Some function
Cleaning up MyResource
我猜这是因为我在语句中做错了什么with
,有效地手动调用了构造函数。我该如何纠正?