Python,调用另一个类中的类函数
您能帮我调用类测试中的广播服务器工厂中的广播功能,请参见所附代码 我尝试过很多从另一个类调用函数的方法,但没有解决方案Python,调用另一个类中的类函数,python,class,call,Python,Class,Call,您能帮我调用类测试中的广播服务器工厂中的广播功能,请参见所附代码 我尝试过很多从另一个类调用函数的方法,但没有解决方案 import sys from twisted.internet import reactor from twisted.python import log from twisted.web.server import Site from twisted.web.static import File from autobahn.websocket import WebSoc
import sys
from twisted.internet import reactor
from twisted.python import log
from twisted.web.server import Site
from twisted.web.static import File
from autobahn.websocket import WebSocketServerFactory, \
WebSocketServerProtocol, \
listenWS
class test():
//call broadcast function from here
class BroadcastServerProtocol(WebSocketServerProtocol):
def onOpen(self):
self.factory.register(self)
def onMessage(self, msg, binary):
if not binary:
self.factory.broadcast("'%s' from %s" % (msg, self.peerstr))
def connectionLost(self, reason):
WebSocketServerProtocol.connectionLost(self, reason)
self.factory.unregister(self)
class BroadcastServerFactory(WebSocketServerFactory):
"""
Simple broadcast server broadcasting any message it receives to all
currently connected clients.
"""
def __init__(self, url, debug = False, debugCodePaths = False):
WebSocketServerFactory.__init__(self, url, debug = debug, debugCodePaths = debugCodePaths)
self.clients = []
self.tickcount = 0
self.tick()
def tick(self):
self.tickcount += 1
self.broadcast("'tick %d' from server" % self.tickcount)
reactor.callLater(1, self.tick)
def register(self, client):
if not client in self.clients:
print "registered client " + client.peerstr
self.clients.append(client)
def unregister(self, client):
if client in self.clients:
print "unregistered client " + client.peerstr
self.clients.remove(client)
def broadcast(self, msg):
print "broadcasting message '%s' .." % msg
for c in self.clients:
c.sendMessage(msg)
print "message sent to " + c.peerstr
if __name__ == '__main__':
if len(sys.argv) > 1 and sys.argv[1] == 'debug':
log.startLogging(sys.stdout)
debug = True
else:
debug = False
ServerFactory = BroadcastServerFactory
#ServerFactory = BroadcastPreparedServerFactory
factory = ServerFactory("ws://localhost:9000",
debug = debug,
debugCodePaths = debug)
factory.protocol = BroadcastServerProtocol
factory.setProtocolOptions(allowHixie76 = True)
listenWS(factory)
webdir = File(".")
web = Site(webdir)
reactor.listenTCP(8080, web)
reactor.run()
同时,大体上
factory = ServerFactory("ws://localhost:9000",
debug = debug,
debugCodePaths = debug)
test(factory)
这将实现您想要的功能,但您似乎缺少了有关类和实例的一些核心概念。对于
test
类要调用另一个类上的任何东西,首先需要有它的实例(静态方法除外)。def\uuuuu init\uuuuuuuuuuuuuuuuuuuuuuuu(工厂):
应该是def\uuuuuu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu,这将用现有的BroadcastServerFactory作为URL参数实例化一个新的BroadcastServerFactory,很可能会出现异常。你想从测试中调用广播,对吗?这就是它的作用。我想你需要考虑一下你真正想要达到的目标,并把它放在你的问题中。我想做的就是广播另一个班级的信息。
factory = ServerFactory("ws://localhost:9000",
debug = debug,
debugCodePaths = debug)
test(factory)