-1

我有以下代码。在 dataReceived 方法中,我试图访问表,但出现错误。如果我使用 self 并完成所有这些工作,它会起作用,但我不想使用 self。使用 self 对我的目的不起作用。我如何在不使用 self 的情况下仍然可以访问 table?

谢谢!

class Table:
    def __init__(self):
        self.players = []
        self.positions = []
        self.id = 0
        self.numberOfPlayers = 0

    def setID(self, _id):
        self.id = _id

    def setActivePlayer(self, player):
        player.countdown = 20
        while player.count > 0:
            print player.countdown
            time.sleep(1)
            player.countdown -= 1

            if player.countdown == 0:
                print "Out of time"

                moves.surrender(player)


class Socket(Protocol):
    table = Table()

    def connectionMade(self):
        #self.transport.write("""connected""")
        self.factory.clients.append(self)
        print "Clients are ", self.factory.clients

    def connectionLost(self, reason):
        self.factory.clients.remove(self)

    def dataReceived(self, data):
        #print "data is ", data
        a = data.split(':')
        if len(a) > 1:
            command = a[0]
            content = a[1]

            b = content.split(';')
            _UDID = b[0].replace('\n', '')

            if command == "Number_of_Players":
                if Socket.table.numberOfPlayers == 0:
                    msg = "%s:TableFound" % _UDID
                elif Socket.table.numberOfPlayers == 1:
                    msg = "%s:Table_Not_Found" % _UDID

        print msg

        for c in self.factory.clients:
                c.message(msg)

    def message(self, message):
        self.transport.write(message)

NUM_TABLES = 10

factories = [ ]
for i in range(0, NUM_TABLES):
    print i
    factory = Factory()
    factory.protocol = Socket
    factory.clients = []
    factories.append(factory)
    reactor.listenTCP(1025+i, factory)
    #print "Blackjack server started"

reactor.run()
4

1 回答 1

1

Try using Socket.table instead of self.table --

By the way: If the method is meant to be static, you can decorate it:

@staticmethod
def dataReceived(data):

[EDIT]: According to the comment section below...

If you want the exact oppssite, you may move the line table = Table() to a newly introduced constructor in the Socket class:

def __init__(self, *args, **kwargs):
    self.table = Table()
    return super(Socket, self).__init__(*args, **kwargs)

After that, you can safely use self.table in the dataReceived method. By the way, the return super(Socket, self).__init__(*args, **kwargs) line just ensures that any constructor of any ancestor class (e.g. Protocol) is called also.

于 2012-06-03T00:00:22.470 回答