【问题标题】:Python, Call a class function from another classPython,从另一个类调用一个类函数
【发布时间】:2013-02-15 09:38:23
【问题描述】:

谁能帮我(菜鸟)从类进程中的类BroadcastServerFactory调用广播函数,按照附加代码 p>

我尝试了很多从另一个类调用函数的方法,但没有解决办法

import time, sys
from apscheduler.scheduler import Scheduler
import threading
import socket
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 process(threading.Thread):
    def __init__(self, buffer3):
        threading.Thread.__init__(self)
        self.setDaemon(True)
        self.buffer3 = buffer3


    def run(self):
        factory.broadcast("I don't know what I'm doing!")



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


class BroadcastPreparedServerFactory(BroadcastServerFactory):
   """
   Functionally same as above, but optimized broadcast using
   prepareMessage and sendPreparedMessage.
   """

   def broadcast(self, msg):
      print "broadcasting prepared message '%s' .." % msg
      preparedMsg = self.prepareMessage(msg)
      for c in self.clients:
         c.sendPreparedMessage(preparedMsg)
         print "prepared message sent to " + c.peerstr


def testing():
    buffer2 - "hello"
    myDisplay = process(buffer2)
    myDisplay.start()


if __name__ == '__main__':

   if len(sys.argv) > 1 and sys.argv[1] == 'debug':
      log.startLogging(sys.stdout)
      debug = True
   else:
      debug = False
   level_scheduler = Scheduler()
   level_scheduler.add_interval_job(testing, seconds=5)
   level_scheduler.start()
   #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()

谢谢

【问题讨论】:

    标签: python class call twisted


    【解决方案1】:

    将要调用的BroadcastServerFactory 的类实例传递给在创建时调用它的类实例process

    class process(threading.Thread):
        def __init__(self, buffer3m, broadcast_server_factory):
            threading.Thread.__init__(self)
            self.setDaemon(True)
            self.buffer3 = buffer3
    
            self.factory = broadcast_server_factory
    
        def run(self):
            self.factory.broadcast("I don't know what I'm doing!")
    

    然后调用它(它在run 语句中分配为self.factory。我看不到你在__main__ 中创建process 类的位置,但它会用类似的东西创建

     p = process(buffer, factory)
    

    除此之外:在 python process -> Process 中使用大写字母作为类名被认为是好的形式

    【讨论】:

    • 大师@你游戏,你是人生的救星。
    • 需要注意的一点是,在问题和答案中都使用线程可能是不正确的,并且有时只会起作用。 broadcast 不是线程安全的,必须在调用 reactor.run 的同一线程中调用。
    猜你喜欢
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    相关资源
    最近更新 更多