【问题标题】:Python interpreter couldn't find the class variable [duplicate]Python解释器找不到类变量[重复]
【发布时间】:2013-11-16 07:12:49
【问题描述】:

我正在尝试创建一个分布式哈希表。有一个线程。但是线程中的run函数找不到我在构造函数中初始化的sock变量。

这里是代码 -

from socket import *
from threading import *

class DHT(Thread):
    def _init_(self):
        self.sock = socket(AF_INET, SOCK_STREAM)
        self.sock.bind(('127.0.0.1', 5000))
        self.sock.listen(1)

    def run(self):
        while 1:
            conn, addr = self.sock.accept()
            data = conn.recv(20)
            message, port, value = data.split("-")
            if message == 'route message':
                self.route_message(port, value)
            elif message == 'check alive':
                self.check_alive(port, value)
            elif message == "new node":
                self.new_node(port, value)
            elif message == "update hash":
                self.update_hash(port, value)
            conn.close()

    def route_message(self, port, value):
        print("Routing Message")
    def check_alive(self, port, value):
        print("Checking Alive")

    def new_node(self, port, value):
        print("New Node")

    def update_hash(self, port, value):
        print("Updating Hash")

if __name__ == '__main__':
    DHT().start()

【问题讨论】:

    标签: python multithreading constructor self class-variables


    【解决方案1】:

    您必须按如下方式更改前几行(这些是双下划线 init 的两边,正如 RyPeck 已经指出的那样):

    class DHT(Thread):
        def __init__(self):
           Thread.__init__(self)
           self.sock = socket(AF_INET, SOCK_STREAM)
    

    DHT 通过初始化 Thread 对象部分和它自己的东西来设置

    【讨论】:

      【解决方案2】:

      Init 作为特殊方法 needs two underscores 在每一侧运行。

      def __init__(self):
          ...
      

      这就是为什么您的套接字不存在的原因。它永远不会被创建。

      所有 Python 的 magic methods 总是被 2 个下划线包围。为了魔法。

      【讨论】:

      • 现在它说 - AttributeError: 'DHT' object has no attribute '_initialized'
      • 在线程中执行任何其他操作之前,您需要调用Thread.__init__()
      • 我应该在 Thread.__init__() 中做什么?
      • 没什么。当您在子类中覆盖它时,您只需要调用 Thread 的 init。它在Thread docs
      • 如果您有其他问题,请创建一个新问题。不能一直回答不相关的问题。
      猜你喜欢
      • 1970-01-01
      • 2015-03-21
      • 2019-08-05
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多