python - 名称错误 : name 'self' is not defined - when trying to post values to different queues

标签 python queue

这是正确的做法吗。我是 python 新手

class main(threading.Thread):
    queueLock = threading.Lock()
    EppQueue = Queue.Queue(1)
    CrQueue = Queue.Queue(1)
    EPP = threading.Thread(name='EPP', target=EPP, args=(0,EppQueue,))
    cr = threading.Thread(name='cr', target=CR, args=(0,CrQueue,))
    EPP.setDaemon(True)
    EPP.start()
    Cr.start()
    self.send_queue("EppQueue","sss")
    self.send_queue("CrQueue","ssds")

    def send_queue(self,queuename,qvalue,b=None):
        if b is None:
            b = self.queuename
        self.queueLock.acquire()
        self.b.put(qvalue)
        self.queueLock.release()

当我运行它时我得到 NameError: name 'self' is not defined ???

最佳答案

变量 self(类方法的第一个参数 - 你可以为它使用任何名称)是指类实例(也称为对象).您在未定义 self 的地方使用 self,就在尚不知道特定对象的类中。

当执行代码 queueLock = threading.lock() ... 等时,您不在类对象(实例)中,而是在类的上下文中,因此您的锁对于类的所有对象都是相同的类(class)。

关于send_queue,它通过类定义并为所有对象所知,因此您无需使用self. 来访问它。

如果您希望在创建实例时执行某些代码,请将其放入 __init__

class main(threading.Thread):
  def __init__(self):
    self.queueLock = threading.Lock() 
    .. some code ... 
    send_queue("EppQueue","sss")
    send_queue("CrQueue","ssds")

关于python - 名称错误 : name 'self' is not defined - when trying to post values to different queues,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9645775/

相关文章:

c++ - 在 C++ 中运行队列的有用方法是什么

python - Pandas Group 通过制作系列;不是 groupby 对象

python - 在Python中读取文件时如何自动处理解压?

python 跨平台应用程序

java - Java 中泛型的队列实现

python - 在 Python 中使用队列模块在线程之间传递值

c# - 排队服务调用

C# - 移动文件 - 队列或多线程

python - Tkinter 不与 Pycharm 配合使用

python - 在 Python Bottle 中返回不同的 mime 类型