Python语句

Cad*_*nge 3 python raii with-statement

我正在试验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()
Run Code Online (Sandbox Code Playgroud)

这是程序的输出:

Constructing MyResource
Entering MyResource
Constructing MyResource
Some function
Cleaning up MyResource
Run Code Online (Sandbox Code Playgroud)

我猜这是因为我在with语句中做错了,有效地手动调用构造函数.我该如何纠正?

Raf*_*ler 19

您不应该从中返回新实例__enter__.相反,返回self(__enter__正在调用的实例.这就是为什么__init__()被调用两次 - 你调用它两次,一次在你的with语句中,一次进入__enter__().这是一个正确的版本:

def __enter__(self):
    print 'Entering MyResource'
    return self
Run Code Online (Sandbox Code Playgroud)


imm*_*tal 6

__init__因为你把它叫了两次,原因是被调用了两次:

一旦你MyResourcewith语句中启动一个对象,当with语句调用时再一次__enter__创建并返回一个不同的实例MyResource

你的__enter__方法应该返回self.