我正在开发一个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类时,Server.Cores 中的对象永远不会被解构。我读到gc在循环引用和带析构函数的类方面都有问题,但是Core对象从来没有引用Server对象(在Core.CoreSocket中只有套接字对象),所以不会创建循环引用。
我通常更喜欢使用with-statement进行资源清理,但在本例中,我需要通过Server类中的许多不同方法发送命令,因此使用with无助于.我还尝试在每个命令上创建和关闭套接字,但是当我需要发送许多命令时,这确实会降低性能。使用weakref模块创建的弱引用也于事无补,因为析构函数在我创建Server对象之后立即被调用。
为什么在gc清理Core对象时,Server对象不被正确地销毁呢?我想我只是忘了一些简单的东西,但我就是找不出它是什么。
或者,在清理对象时,是否有更好的方法关闭这些套接字?
发布于 2013-12-03 02:23:47
您混淆了类和实例成员。与其他语言不同,在类作用域中定义变量会创建类变量,而不是实例变量。当Server实例死亡时,Server类仍然存在,并且仍然保存对核心的引用。相反,在self.cores方法中定义__init__:
class Server(object):
def __init__(self):
self.cores = []https://stackoverflow.com/questions/20341650
复制相似问题