为什么我会收到AttributeError: Object has no attribute错误?[已关闭]

9 浏览
0 Comments

为什么我会收到AttributeError: Object has no attribute错误?[已关闭]

我有一个类MyThread,在这个类中有一个方法sample。我试图在同一个对象上下文中运行它。请看代码:

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter, redisOpsObj):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
        self.redisOpsObj = redisOpsObj
    def stop(self):
        self.kill_received = True
    def sample(self):
        print "Hello"
    def run(self):
        time.sleep(0.1)
        print "\n Starting " + self.name
        self.sample()

看起来非常简单,不是吗?但是当我运行它时,我得到这个错误:

AttributeError: 'myThread' object has no attribute 'sample'现在我就是在那里定义了这个方法。那么问题出在哪里呢?请帮忙解决。

编辑:这是堆栈跟踪

Starting Thread-0
Starting Thread-1
Exception in thread Thread-0:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner
self.run()
File "./redisQueueProcessor.py", line 51, in run
self.sample()
AttributeError: 'myThread' object has no attribute 'sample'
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.6/threading.py", line 525, in __bootstrap_inner
self.run()
File "./redisQueueProcessor.py", line 51, in run
self.sample()
AttributeError: 'myThread' object has no attribute 'sample'

我是这样调用它的:

arThreads = []
maxThreads = 2;
for i in range( maxThreads ):
    redisOpsObj = redisOps()
    arThreads.append( myThread(i, "Thread-"+str(i), 10, redisOpsObj) )

抱歉,我不能发布redisOps类的代码。但我可以向您保证它可以正常工作。

0