Python __enter__ / __exit__ vs __init__ (or __new__) / __del__

前端 未结 3 1781
一整个雨季
一整个雨季 2021-02-05 05:23

I have searched and I\'m unable to come up with any good reason to use python\'s __enter__ /__exit__ rather than __init__ (or __new_

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 05:47

    del x doesn’t directly call x.__del__()

    You have no control over when .__del__ is called, or in fact whether it gets called at all.

    Therefore, using __init__/__del__ for context management is not reliable.

提交回复
热议问题