这是正确的做法吗?我是一个新手
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()
当我运行这个时,我得到名称错误:没有定义名称“self”???
不能对类变量/函数使用“self”。可以对类的实例使用“self”。。。
例如:
x是一个类变量。B的self.x是一个实例变量。。!!
同时也用于调用类的函数..最佳实践是创建该类的实例(对象)并用该对象调用函数。。!!
比如:
对于要在“实例”创建上运行的代码,请将该代码放入
__init__():
函数变量
self
(类方法的第一个参数-您可以对其使用任何名称)是指类实例(也称为对象)。在没有定义self的地方使用self,就在还不知道特定对象的类中使用。当代码queueLock=threading.lock()时。。。etc,不是在类对象(实例)中执行的,而是在类的上下文中执行的,因此对于类的所有对象,锁都是相同的。
关于
send_queue
,它是通过类定义并为所有对象所知的,因此不需要使用self.
来访问它。如果要在实例创建时执行一些代码,请将其放入
__init__
。请确保
send_queue
函数是主类的一部分。^ {< CD2}}类似于C++中的^ {CD3}}指针,需要与类关联。send_queue
函数应该与main
类一起缩进相关问题 更多 >
编程相关推荐