python - 为什么在 "variable"中使用 self (引用?)?

标签 python self

我开始学习/编写 Twisted 网络编程,我遇到了以下代码:

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)

self.x[y]=self有什么好处?

最佳答案

self.factory.users是一个共享映射;该类的每个实例都可以访问它。如果您愿意的话,它是连接实例的中央注册表。连接本身负责注册自身

通过在 self.factory.users 中存储对所有每用户实例的引用然后,您可以向 broadcastMessage 中的所有用户发送消息。方法:

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

这会循环所有已注册的实例,并调用 sendLine()在每个其他连接上。

关于python - 为什么在 "variable"中使用 self (引用?)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25040812/

相关文章:

ios - 获取组件的变量名

php - 特质; PHP 5.4 中的 parent 和 self 类型提示

javascript - 使用 FastAPI 和 JS 提取上传 .csv

python - 如何在 tensorflow 中顺序和随机读取 tf.data.Iterator ?

python - SVM决策函数: visualizing class separation

python - 为什么我需要将对象传递给此类才能使其工作?

ios - block 中的宏捕获 self

python - 在 Mac OS X Sierra 上为 Django Python 安装 mysqlclient

python - 没有给出参数时选择解析器打印使用帮助

python - 如何在不明确接受的情况下让自己进入 Python 方法