2014-12-03 37 views
1

我想設置它,使屬性「實例」是自動增量。我一直在尋找,但我也是新來的套接字編程,所以我可能一直在問錯誤的問題。最終目標是創建一個聊天室,可以識別誰在哪個組中。我一直在網上找到的所有教程都只能顯示一個非常簡單的套接字連接聊天室,而沒有詳細說明服務器應該如何區分不同的組。 我想我需要做到這一點的唯一的事情是讓該變量而不是自動遞增每個新用戶加入每當有人新連接在我的扭曲套接字重置屬性[python]

from twisted.internet.protocol import Factory, Protocol 
from twisted.internet import reactor 
import json 
class IphoneChat(Protocol): 
    memberList={} 
    Instance = 1 
    def connectionMade(self): 
     print "a client connected" 
     self.factory.clients.append(self) 
     print self.Instance 
     self.Instance+=1 
     self.factory.clients[-1].message("Connection Success") 
    def connectionLost(self, reason): 
     self.factory.clients.remove(self) 
    def dataReceived(self, data): 

     json_decoded = json.loads(data) 
     Type=json_decoded[0]["type"] 
     groupID=json_decoded[0]["groupID"] 
     member=json_decoded[0]["member"] 
     print Type 
     if Type=="node": 
      print "Node recc" 
     elif Type=="create": 
      print "group created" 
      self.memberList[groupID]=[] 
     elif Type=="con": 
      print "Connection" 
      self.memberList[groupID].append(member) 
     elif Type=="dis": 
      print "Disconnect" 
      self.memberList[grouID].remove(member) 
     elif Type=="poll": 
      print "Poll" 
     elif Type=="comment": 
      print "Comment" 
     else : 
      print "unrecognized type" 

     a = data.split(':') 
     print a 
     if len(a) > 1 : 
      command = a[0] 
      content = a[1] 
      msg = "" 
      if command == 'iam' : 
       self.name = content 
       msg = self.name + "has joined" 
      elif command == "msg" : 
       msg = self.name + ": " + content 
       print msg 
      for c in self.factory.clients: 
       c.message(msg) 
    def message(self, message): 
     self.transport.write(message +"\n") 

回答

2

這裏的問題時進行復位的是,+ =遞增的實例值而不是類本身(這意味着在您使用+=後,實例現在具有2的計數,但類級變量具有原始計數)。要解決這個問題,只需將類型(即類級字典)上的值與實例進行遞增。這是一個最簡單的例子,應該讓事情更清楚。

class CountingClass(object): 
    count = 1 


>>> obj = CountingClass() 
>>> obj.count += 1 
>>> obj.count 
2 
>>> CountingClass.count 
1 
>>> CountingClass.count += 1 
>>> CountingClass.count 
2 
>>> type(obj).count += 1 
>>> CountingClass.count 
3 

您應該使用type(obj)如果你想子類有不同的計數(因爲他們將各自有自己的數據__dict__),否則你應該明確地使用實際的類名。

+0

我還有一點想弄明白,但我給你最好的答案,讓我看看我在概念上出錯的地方,我想我可以從這裏算出來,謝謝一堆! – DanHabib 2014-12-03 04:48:07