- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
知道为什么我在运行下面的代码时会收到以下错误:
Traceback (most recent call last):
File "C:\pytests\mthread1.py", line 25, in <module>
thread1 = myThread(1, "Thread-1", 1)
File "C:\pytests\mthread1.py", line 9, in __init__
self.name = name
AttributeError: 'myThread' object has no attribute '_initialized'
代码:
import time
import threading
exitFlag = 0
class myThread(threading.Thread):
def __init__(self, threadID, name, counter):
self.threadID = threadID
self.name = name
self.counter = counter
threading.Thread.__init__(self)
def run(self):
print("Starting ", self.name)
print_time(self.name, self.counter, 5)
print("Exiting ", self.name)
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
thread.exit()
time.sleep(delay)
print("{}: {}" . format(threadName, time.ctime(time.time())))
counter -= 1
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
thread1.start()
thread2.start()
print("Exiting Main Thread")
最佳答案
很简单,根据documentation :
A thread has a name. The name can be passed to the constructor, and read or changed through the name attribute.
和
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
因此,您正在尝试通过类构造函数设置一个可能期望以某种方式设置的属性。事实上,如果您检查 Thread
类' source code :
@property
def name(self):
assert self._initialized, "Thread.__init__() not called"
return self._name
@name.setter
def name(self, name):
assert self._initialized, "Thread.__init__() not called"
self._name = str(name)
所有你需要改变的 - 稍早调用 Thread.__init__(name=name)
:
class myThread(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self, name=name)
self.threadID = threadID
self.counter = counter
关于python - 属性错误 : 'myThread' object has no attribute '_initialized' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15316428/
我有一个方法,在第二个线程中被调用: public byte[] ReadAllBytesFromStream(Stream input) { clock.Start(
这个问题在这里已经有了答案: "implements Runnable" vs "extends Thread" in Java (42 个答案) 关闭 9 年前。 更好的帖子:"implement
在表单中,我有一个按钮“中止”。在它上面我添加了 mythread.terminate 用于终止线程。现在,在执行方法中,我使用变量 termerated 并管理它。但是当我没有循环,而是一条需要很多
今天,Java的盛行宗教严重禁止在stop() [1] [2] [3]上使用Thread实例方法。在official documentation中将其标记为(已弃用的),并显示以下消息: This m
Thread td = new Thread(){ public void run(){ //do someting Thread.slee
知道为什么我在运行下面的代码时会收到以下错误: Traceback (most recent call last): File "C:\pytests\mthread1.py", line 25,
我查看了这个 api,但没有找到我要查找的信息: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.State.html#RU
我正在编写一个多线程服务器,但在“mythraed”类的编译过程中出现以下错误:1) 无法连接 (null)::readyRead() 到 mythread::readyRead()2) 无法连接 (
我是一名优秀的程序员,十分优秀!