Python의 '_enter__' 및 '_exit__' 설명
누군가의 암호에서 이걸 봤어그것은 무엇을 뜻하나요?
def __enter__(self):
return self
def __exit__(self, type, value, tb):
self.stream.close()
from __future__ import with_statement#for python2.5
class a(object):
def __enter__(self):
print 'sss'
return 'sss111'
def __exit__(self ,type, value, traceback):
print 'ok'
return False
with a() as s:
print s
print s
의 방법마법)을 __enter__
,__exit__
하면 에서 할 수 할 수 있습니다.with
★★★★★★ 。
정도의 한 코드를 할 수 하는 입니다(「 다운」코드로 생각해 ).try-finally
블록)을 클릭합니다.여기에 더 많은 설명이 있습니다.
유용한 예로는 데이터베이스 연결 개체(대응하는 'with' 문이 범위를 벗어나면 연결이 자동으로 닫힙니다)가 있습니다.
class DatabaseConnection(object):
def __enter__(self):
# make a database connection and return it
...
return self.dbconn
def __exit__(self, exc_type, exc_val, exc_tb):
# make sure the dbconnection gets closed
self.dbconn.close()
...
와 같이 이 는 '''와 합니다.with
할 수 )from __future__ import with_statement
Python 2.5)는 Python 2.5를 사용합니다.
with DatabaseConnection() as mydbconn:
# do stuff
PEP343 - 'with' 스테이트먼트에도 훌륭한 글이 있습니다.
콘텍스트 매니저가 무엇인지 알고 있다면 더 이상 이해할 필요가 없습니다.__enter__
★★★★★★★★★★★★★★★★★」__exit__
예를 들어 .매우 간단한 예를 보겠습니다.
이 예에서는 myfile을 엽니다.txt 파일을 엽니다.try/finally 블록은 예기치 않은 예외가 발생하더라도 myfile을 확실하게 보호합니다.txt가 닫힙니다.
fp=open(r"C:\Users\SharpEl\Desktop\myfile.txt")
try:
for line in fp:
print(line)
finally:
fp.close()
다음 문장으로 같은 파일을 엽니다.
with open(r"C:\Users\SharpEl\Desktop\myfile.txt") as fp:
for line in fp:
print(line)
코드를 보시면, 저는 파일을 닫지 않았고, 차단 시도/최종 차단은 없습니다.statement를 사용하면 myfile.txt가 자동으로 닫히기 때문입니다.전화로도 확인할 수 있습니다.print(fp.closed)
아트리뷰트 -- 아트리뷰트 --가 됩니다.True
.
이는 오픈 함수에 의해 반환되는 파일 객체(이 예에서는 fp)에는 2개의 메서드가 포함되어 있기 때문입니다.__enter__
★★★★★★★★★★★★★★★★★」__exit__
콘텍스트 매니저라고도 합니다. __enter__
method는 의 시작 부분에서 block과 함께 호출됩니다.__exit__
메서드라고 .
주의: 스테이트먼트에서는 컨텍스트 관리 프로토콜을 지원하는 오브젝트만 사용할 수 있습니다.__enter__
★★★★★★★★★★★★★★★★★」__exit__
컨텍스트 라고 불립니다.두 메서드를 모두 구현하는 클래스를 컨텍스트 매니저 클래스라고 합니다.
이제 독자적인 콘텍스트 매니저 클래스를 정의합니다.
class Log:
def __init__(self,filename):
self.filename=filename
self.fp=None
def logging(self,text):
self.fp.write(text+'\n')
def __enter__(self):
print("__enter__")
self.fp=open(self.filename,"a+")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("__exit__")
self.fp.close()
with Log(r"C:\Users\SharpEl\Desktop\myfile.txt") as logfile:
print("Main")
logfile.logging("Test1")
logfile.logging("Test2")
두 가지 모두에 대한 .__enter__
★★★★★★★★★★★★★★★★★」__exit__
마법의 방법
Python에 를 찾는 이 이상하게 것을 알게 .__enter__
★★★★★★★★★★★★★★★★★」__exit__
다른 사람을 돕기 위한 링크는 다음과 같습니다.
https://docs.python.org/2/reference/datamodel.html#with-statement-context-managershttpsdocs.python.org/2/reference/datamodel.html#
https://docs.python.org/3/reference/datamodel.html#with-statement-context-managershttpsdocs.python.org/3/reference/datamodel.html#
버전에서도 (어느 버전에서도 동일)
object.__enter__(self)
이 개체와 관련된 런타임 컨텍스트를 입력합니다.with
는 이( 경우statement는 이 메서드의 반환값을 any로 지정합니다.
object.__exit__(self, exc_type, exc_value, traceback)
이 개체와 관련된 런타임 컨텍스트를 종료합니다.파라미터는 콘텍스트를 종료시킨 예외를 나타냅니다. 모두 "3이 .None
.
예외가 제공되었을 때 메서드가 예외를 억제(즉, 전파되지 않도록)하는 경우 True 값을 반환해야 합니다.그렇지 않으면 이 메서드를 종료하면 예외가 정상적으로 처리됩니다.
:
__exit__()
메서드는 전달된 예외를 다시 발생시키지 않습니다.이치노
난 이 사건에 대한 명확한 설명을 듣고 싶었거든__exit__
방법★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
★★★★★★★★★★★★★★★★★.exc_type
외외클클 클다다다다다
통과 예외를 다시 올리지 말라고 되어 있습니다.이는 인수 중 하나가 실제 예외 인스턴스일 수도 있고 유형 및 값에서 직접 인스턴스화할 수도 있음을 시사합니다.
할 수 .
http://effbot.org/zone/python-with-statement.htmhttpeffbot.org/zone/.htm
들면 다음과 같은 .
__exit__
삼키지만 는 method "TypeError"를합니다.
def __exit__(self, type, value, traceback):
return isinstance(value, TypeError)
선명하게...너무 선명하게value
을 사용하다
그리고 아마traceback
는 Python 트레이스백오브젝트입니다
추가 문서는 다음과 같습니다.
https://docs.python.org/3/library/stdtypes.html#context-manager-typeshttpsdocs.python.org/3/library/stdtypes.html#
은 ...에 대해 더 있다.그쪽에서 조금 더 자세한 설명을 하고 있습니다.__enter__
★★★★★★★★★★★★★★★★★」__exit__
특히 더 명확하다.__exit__
또는 합니다). 암묵적인 falsey는 falsey이다(truthy 또는 falsey는 정상적으로 동작합니다).None
되돌아가다
호출 순서를 예시하기 위한 위의 답변과 더불어 간단한 실행 예도 있습니다.
class MyClass:
def __init__(self):
print("__init__")
def __enter__(self):
print("__enter__")
def __exit__(self, type, value, traceback):
print("__exit__")
def __del__(self):
print("__del__")
with MyClass():
print("body")
출력을 생성합니다.
__init__
__enter__
body
__exit__
__del__
사용 시: " " " " "with MyClass() as my_handler
에서 반환되는 __enter__()
의 " " " " "None
! 이러한 용도로는 다음과 같은 반환값을 정의해야 합니다.
def __enter__(self):
print('__enter__')
return self
이것은 컨텍스트 매니저라고 불리며 다른 프로그래밍 언어에도 유사한 접근 방식이 존재함을 추가하고 싶습니다.비교는 python의 컨텍스트 매니저를 이해하는 데 도움이 될 수 있습니다.기본적으로 컨텍스트 매니저는 초기화할 필요가 있는 자원(파일, 네트워크, 데이터베이스)을 처리할 때 사용되며, 어느 시점에서 해체(폐기)될 때 사용됩니다.Java 7 이상에서는 다음과 같은 형태로 자동 자원 관리가 제공됩니다.
//Java code
try (Session session = new Session())
{
// do stuff
}
은 Session을 구현해야 .AutoClosable
또는 그 (다수의) 서브 인터페이스의 1개입니다.
C#에는 다음 형식의 리소스를 관리하기 위한 명령어가 있습니다.
//C# code
using(Session session = new Session())
{
... do stuff.
}
경우, 「」는Session
.IDisposable
python에서는 사용하는 클래스가 구현되어야 합니다.__enter__
★★★★★★★★★★★★★★★★★」__exit__
하다
#Python code
with Session() as session:
#do stuff
또한 다른 사람들이 지적한 바와 같이 모든 언어로 try/finally 문을 사용하여 동일한 메커니즘을 구현할 수 있습니다.이건 그냥 통사설탕이에요.
답변을 추가해 보십시오(배울 생각).
__enter__
★★★★★★★★★★★★★★★★★」[__exit__]
둘 다 "with 스테이트먼트"(PEP 343)의 본문 출입 시 호출되는 방식이며, 양쪽의 실장은 컨텍스트 매니저라고 불립니다.
with 스테이트먼트는 try final 절의 흐름 제어를 숨기고 코드를 불가해하게 하는 것을 의도하고 있습니다.
with 문의 구문은 다음과 같습니다.
with EXPR as VAR:
BLOCK
즉, (PE 343에 기재된 바와 같이) 다음과 같습니다.
mgr = (EXPR)
exit = type(mgr).__exit__ # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
try:
VAR = value # Only if "as VAR" is present
BLOCK
except:
# The exceptional case is handled here
exc = False
if not exit(mgr, *sys.exc_info()):
raise
# The exception is swallowed if exit() returns true
finally:
# The normal and non-local-goto cases are handled here
if exc:
exit(mgr, None, None, None)
코드를 시험해 보세요.
>>> import logging
>>> import socket
>>> import sys
#server socket on another terminal / python interpreter
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.listen(5)
>>> s.bind((socket.gethostname(), 999))
>>> while True:
>>> (clientsocket, addr) = s.accept()
>>> print('get connection from %r' % addr[0])
>>> msg = clientsocket.recv(1024)
>>> print('received %r' % msg)
>>> clientsocket.send(b'connected')
>>> continue
#the client side
>>> class MyConnectionManager:
>>> def __init__(self, sock, addrs):
>>> logging.basicConfig(level=logging.DEBUG, format='%(asctime)s \
>>> : %(levelname)s --> %(message)s')
>>> logging.info('Initiating My connection')
>>> self.sock = sock
>>> self.addrs = addrs
>>> def __enter__(self):
>>> try:
>>> self.sock.connect(addrs)
>>> logging.info('connection success')
>>> return self.sock
>>> except:
>>> logging.warning('Connection refused')
>>> raise
>>> def __exit__(self, type, value, tb):
>>> logging.info('CM suppress exception')
>>> return False
>>> addrs = (socket.gethostname())
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> with MyConnectionManager(s, addrs) as CM:
>>> try:
>>> CM.send(b'establishing connection')
>>> msg = CM.recv(1024)
>>> print(msg)
>>> except:
>>> raise
#will result (client side) :
2018-12-18 14:44:05,863 : INFO --> Initiating My connection
2018-12-18 14:44:05,863 : INFO --> connection success
b'connected'
2018-12-18 14:44:05,864 : INFO --> CM suppress exception
#result of server side
get connection from '127.0.0.1'
received b'establishing connection'
이제 수동으로 시도합니다(변환 구문 변경):
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #make new socket object
>>> mgr = MyConnection(s, addrs)
2018-12-18 14:53:19,331 : INFO --> Initiating My connection
>>> ext = mgr.__exit__
>>> value = mgr.__enter__()
2018-12-18 14:55:55,491 : INFO --> connection success
>>> exc = True
>>> try:
>>> try:
>>> VAR = value
>>> VAR.send(b'establishing connection')
>>> msg = VAR.recv(1024)
>>> print(msg)
>>> except:
>>> exc = False
>>> if not ext(*sys.exc_info()):
>>> raise
>>> finally:
>>> if exc:
>>> ext(None, None, None)
#the result:
b'connected'
2018-12-18 15:01:54,208 : INFO --> CM suppress exception
이전과 같은 서버 측의 결과
제 서투른 영어실력과 불명확한 설명에 대해 사과드립니다.
이 Python을 __enter__
실행이 with 스테이트먼트의 컨텍스트에 들어가 리소스를 취득할 때.다시 은 Python을 합니다.__exit__
을
Context Managers와 Python의 "with" 스테이트먼트에 대해 생각해 보겠습니다.Context Manager는 단순한 "프로토콜"(또는 인터페이스)로 오브젝트가 와 함께 사용할 수 있도록 해야 합니다.기본적으로 컨텍스트 매니저로서 기능하도록 하려면 객체에 엔터 메서드와 종료 메서드를 추가하면 됩니다.Python은 자원 관리 사이클에서 적절한 시기에 이 두 가지 메서드를 호출합니다.
이것이 실제적인 관점에서 어떻게 보일지 살펴보겠습니다.open() 컨텍스트 매니저의 간단한 실장은 다음과 같습니다.
class ManagedFile:
def __init__(self, name):
self.name = name
def __enter__(self):
self.file = open(self.name, 'w')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
Managed File 클래스는 컨텍스트 매니저 프로토콜을 따르며 이제 with 문을 지원합니다.
>>> with ManagedFile('hello.txt') as f:
... f.write('hello, world!')
... f.write('bye now')`enter code here`
Python 호출은 실행이 with 스테이트먼트의 컨텍스트에 들어가 리소스를 취득할 때 입력합니다.실행이 다시 컨텍스트를 벗어나면 Python은 exit을 호출하여 리소스를 해방합니다.
Python에서 with 문을 지원하는 유일한 방법은 클래스 기반 컨텍스트 매니저를 작성하는 것이 아닙니다.표준 라이브러리의 contextlib 유틸리티 모듈은 기본 컨텍스트 매니저 프로토콜 위에 구축된 몇 가지 추상화를 제공합니다.따라서 사용 사례가 contextlib에서 제공하는 것과 일치하면 생활이 조금 더 쉬워질 수 있습니다.
언급URL : https://stackoverflow.com/questions/1984325/explaining-pythons-enter-and-exit
'programing' 카테고리의 다른 글
PHP - false일 때 bool이 false를 에코하도록 합니다. (0) | 2022.09.25 |
---|---|
"0을 제외한 모든 양의 정수"의 정규식은 무엇입니까? (0) | 2022.09.25 |
거즐의 예외 포착 (0) | 2022.09.25 |
LAN에서 Debian 9(Stretch)의 MariaDB 10.1.23에 접속 (0) | 2022.09.25 |
소수점 두 자리 숫자 표시 (0) | 2022.09.25 |