如何在python中获取类的实例

2024-10-01 11:24:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过websockets创建一个客户端来编写一些测试用例来评估服务器的响应。我用高速公路建立联系。但是,由于我当前无法发送消息,因此我无法在该类中发送消息。代码如下:

class SlowSquareClientProtocol(WebSocketClientProtocol):

    def onOpen(self):      
        print "Connection established"

    def onMessage(self, payload, isBinary):
        if not isBinary:
            res = json.loads(payload.decode('utf8'))
            print("Result received: {}".format(res))
            self.sendClose()

    def onClose(self, wasClean, code, reason):
        if reason:
            print(reason)
        reactor.stop()

class NLVRTR(TestFixture,SlowSquareClientProtocol):
    @classmethod
    def setUpClass(self):        
        log.startLogging(sys.stdout)
        factory = WebSocketClientFactory(u"ws://someURL:8078")
        factory.protocol = SlowSquareClientProtocol
        reactor.connectTCP("someURL", 8078, factory)
        wsThread = threading.Thread(target = reactor.run, 
            kwargs={'installSignalHandlers':0})
        wsThread.start()

    def test_00_simple(self):
        WSJsonFormatter = WSformat()
        x = WSJsonFormatter.formatGetInfo(2)
        self.sendMessage(json.dumps(x).encode('utf8'))
        print("Request to square {} sent.".format(x))

因此,为了详细说明,我在setUpClass方法中启动了客户机,并尝试在test_00_simple中发送一些消息。然而,我似乎遇到了这样的错误

^{pr2}$

状态应该是在WebSocketClientProtoco中定义的属性。如果我将sendmessage放在onOpen方法中,一切都会正常工作,但是除了SlowSquareClientProtocol类之外,我不能从其他任何地方调用它。在高速公路的文件中提到

Whenever a new client connects to the server, a new protocol instance will be created

我认为这就是问题所在,它会创建一个新的协议实例,sendmages方法正在使用该实例。既然我不是在慢车里叫它。。。类时,sendmessage在客户端连接时从未捕捉到此新创建的协议,因此出现错误。我的问题是,有没有什么方法可以在客户端连接后通过代码获取新创建的实例?在


Tags: 实例方法代码self消息客户端factorydef
1条回答
网友
1楼 · 发布于 2024-10-01 11:24:46

我发现了一个愚蠢的方法来解决这个问题,使用垃圾收集器来检索实例,如下所示

#Used to get the instance of the protocol
def getIn(self):
    for obj in gc.get_objects():
        if isinstance(obj, SlowSquareClientProtocol):
            protocol = obj
    return protocol

def test_00_startSession(self):
    WSJsonFormatter = WSformat()
    x = WSJsonFormatter.formatCreateSession("eng-USA", sessionId = "837ab900-912e-11e6-b83e-3f30a2b99389")
    SlowSquareClientProtocol.sendMessage(self.getIn(),json.dumps(x).encode('utf8'))
    print("Request {} sent.".format(x))

因此,我搜索了所有具有我要查找的类名称的实例,然后在sendmessage方法中传递它。我仍然愿意接受其他更简单的建议:)

相关问题 更多 >