我有以下代码。在dataReceived方法中,我试图访问表,但是我收到错误。如果我使用自我并完成所有这些工作,它会起作用,但我不想使用自我。使用自我不适用于我的目的。如何在不使用自我的情况下仍然可以访问表格?
谢谢!
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()
答案 0 :(得分:1)
尝试使用Socket.table
代替self.table
-
顺便说一句:如果方法是静态的,你可以装饰它:
@staticmethod
def dataReceived(data):
[编辑]:根据下面的评论部分......
如果您想要确切的反对意见,可以将table = Table()
行移动到Socket
类中新引入的构造函数:
def __init__(self, *args, **kwargs):
self.table = Table()
return super(Socket, self).__init__(*args, **kwargs)
之后,您可以在self.table
方法中安全地使用dataReceived
。
顺便说一句,return super(Socket, self).__init__(*args, **kwargs)
行只确保调用任何祖先类的任何构造函数(例如Protocol
)。