我正在开发一个python程序来监视和控制游戏服务器.游戏服务器有许多游戏核心,这些核心处理客户端.
我有一个叫做类的Server
实例的python类Core
,这些实例用于管理实际的游戏核心.本Core
类需要通过TCP-套接字连接到游戏的核心,以发送命令到特定游戏的核心.要正确关闭这些套接字,Core
该类有一个__del__
关闭套接字的方法.
一个例子:
class Server(object): Cores = [] # list which will be filled with the Core objects def __init__(self): # detect the game-cores, create the core objects and append them to self.Cores class Core(object): CoreSocket = None # when the socket gets created, the socket-object will be bound to this variable def __init__(self, coreID): # initiate the socket connection between the running game-core and this python object def __del__(self): # properly close the socket connection
现在,当我使用Core
类本身时,析构函数总是被正确调用.但是当我使用这个Server
类时,Core
里面的对象Server.Cores
永远不会被破坏.我已经读过gc有循环引用和带析构函数的类的问题,但是Core
对象从不引用该Server
对象(只有socket-object,in Core.CoreSocket
),因此不会创建循环引用.
我通常更喜欢使用with
-statement进行资源清理,但在这种情况下我需要通过类中的许多不同方法发送命令Server
,因此使用with
无济于事...我还尝试在每个命令上创建并关闭套接字,但是当我需要发送许多命令时,这真的会杀死性能.使用该weakref
模块创建的弱参考将无济于事,因为在创建Server
对象后立即调用析构函数.
Core
当Server
物体被gc清理干净时,为什么物体不能被正确地破坏?我想我只是忘记了简单的事情,但我无法找出它是什么.
或者,当对象被清理时,可能有更好的方法来关闭这些套接字?
你混淆了类和实例成员.与其他一些语言不同,在类范围定义变量会创建一个类变量,而不是实例变量.当一个Server
实例死亡时,Server
该类仍然存在,并且仍然保留对核心的引用.改为self.cores
在__init__
方法中定义:
class Server(object): def __init__(self): self.cores = []