python 让对象支持上下文管理协议

2022-05-27  本文已影响0人  孙广宁
8.3 通过with语句出发,让对象支持上下文管理协议
>>> from socket import socket,AF_INET,SOCK_STREAM
>>> class LC:
...     def __init__(self,address,family=AF_INET,type=SOCK_STREAM):
...         self.address=address
...         self.family=AF_INET
...         self.type=SOCK_STREAM
...         self.sock=None
...     def __enter__(self):
...         if self.sock is not None:
...             raise RuntimeError("Already connected")
...         self.sock = sock(self.family,self.type)
...         self.sock.connect(self.address)
...         return self.sock
...     def __exit__(self,exc_ty,exc_val,tb):
...         self.sock.close()
...         self.sok = None
...
>>> from functools import partial
>>> con = LC("www.baidu.com",80)
>>> with con as s:
...     s.send(b'GET /index.html HTTP/1.0\r\n')
...     s.send(b'HOST: www.baidu.com\r\n')
...     s.send(b'\r\n')
...     resp = b''.join(iter(partial(s.recv,8192),b''))
...
上一篇下一篇

猜你喜欢

热点阅读