我是Python的新手,我想我正在尝试做一些简单的事情。然而,我对我得到的结果感到困惑。我声明了一个类,它有两个类方法,add和remove,在我的简单示例中,这两个方法在list类变量中添加或删除一个客户端。下面是我的代码:
Service.py
from Client import Client
class Service:
clients = []
@classmethod
def add(cls, client):
cls.clients.append(client)
@classmethod
def remove(cls, client):
if client in cls.clients:
cls.clients.remove(client)
if __name == '__main__'
a = Client()
b = Client()
c = Client()
Service.add(a)
Service.add(b)
Service.add(c)
print(Service.clients)
c.kill()
print(Service.clients)
Service.remove(c)
print(Service.clients)Client.py
class Client:
def kill(self):
from Service import Service
Service.remove(self)我预计调用c.kill()会将实例从客户端列表中删除。但是,当我评估客户列表时,它显示0个项目。当我调用Service.remove(c)时,它会显示正确的列表,并按预期删除它。我不确定我在这里遗漏了什么。
如果重要的话,我目前使用的是PyCharm,我的代码在Python3.6.5的Virtualenv中运行。
发布于 2018-08-02 20:29:40
您当前的代码正在使用循环导入,因为这两个文件相互利用。此外,不依赖于客户端来销毁连接,而是使用contextmanager来促进clients的更新,并在过程结束时使用空clients
import contextlib
class Client:
pass
class Service:
clients = []
@classmethod
def add(cls, client):
cls.clients.append(client)
@classmethod
@contextlib.contextmanager
def thread(cls):
yield cls
cls.clients = []
with Service.thread() as t:
t.add(Client())
t.add(Client())https://stackoverflow.com/questions/51653564
复制相似问题