gpt4 book ai didi

python - 属性错误 : 'myThread' object has no attribute '_initialized'

转载 作者:太空狗 更新时间:2023-10-30 02:33:01 25 4
gpt4 key购买 nike

知道为什么我在运行下面的代码时会收到以下错误:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com