당신이하고있는 일은 완전히 멋지다. contextlib
표준 라이브러리에는 이미 비슷한 기능이 있지만 Close
메서드의 이름을 close
으로 바꿔야합니다.
import contextlib
with contextlib.closing(thing):
print thing
이 대신 사용하는 것이 좋습니다. 결국 Python 메소드의 권장 명명 규칙은 all_lowercase_with_underscores
입니다.
class Foo(object):
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.fd = open(self.filename)
def __exit__(self, exc_type, exc_value, traceback):
self.fd.close()
그리고 사용 : 입력하고 블록 with
을 떠날 때
with Foo('/path/to/file') as foo:
# do something with foo
방법 __enter__
및 __exit__
이 암시 적으로 호출됩니다
출처
2013-08-12 06:36:57
tom
좋아 보인다. 클래스에서 소멸자를 사용할 수도 있습니다. – akiniwa
소멸자 (예 :'__del__')를 사용하지 않는 것이 좋습니다. 언제 전화가 왔는지에 대해 추론하기는 정말로 어렵습니다. 여기에 허용 된 대답을 참조하십시오 : http://stackoverflow.com/questions/1935153/del-method-being-called-in-python-when-it-is-not-expected – tom