1. 上下文管理器
语法: with 对象 as 变量名
2. 使用上下文管理器
对象想要使用,则需要对象内部定义__enter__方法和__exit__方法
class Client(object):
def __init__(self,ip,port):
self.ip = ip
self.port = port
def recv(self):
pass
def __enter__(self):
self.c = socket.socket()
self.c.connect(self.ip,self.port)
return self # 即as后面的对象
def__exit__(self,exc_type,exc_val,exc_tb):
self.c.close()
with Client('127.0.0.1',8080) as c:
c.recv()