Aris Breezy
Aris Breezy

Reputation: 13

why use the self (reference?) in a "variable"?

I started studying / writing Twisted network programming and I came across with the following code:

def handle_REGISTER(self, name):
     if name in self.factory.users:
        self.sendLine("Name taken, please choose another.")
        return
     self.sendLine("Welcome, %s!" % (name,))
     self.broadcastMessage("%s has joined the channel." % (name,))
     self.name = name
     self.factory.users[name] = self
     self.state = "CHAT"

def handle_CHAT(self, message):
     message = "<%s> %s" % (self.name, message)
     self.broadcastMessage(message)

def broadcastMessage(self, message):
     for name, protocol in self.factory.users.iteritems():
        if protocol != self:
           protocol.sendLine(message)

what the benefits from self.x[y]=self?

Upvotes: 1

Views: 124

Answers (2)

Aaron Digulla
Aaron Digulla

Reputation: 328624

The code uses the self-reference in two ways:

  1. To determine if a name in the chatroom is already taken
  2. To send everyone else a message (i.e. to prevent to send a copy of the message to the user who wrote it).

To achieve #2, they iterate over all items in the dict self.factory.users. The keys are users in the chatroom. Values are instances of the chat.

When protocol != self, then the code has found an instance which doesn't belong to the current user.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122372

self.factory.users is a shared mapping; each and every instance of this class can access it. It is a central registry of connection instances, if you will. The connection itself is made responsible for registering itself.

By storing references to all the per-user instances in self.factory.users you can then send messages to all users, in the broadcastMessage method:

for name, protocol in self.factory.users.iteritems():
    if protocol != self:
        protocol.sendLine(message)

This loops over all registered instances, and calls sendLine() on each and every other connection.

Upvotes: 1

Related Questions