Python AttributeError:对象没有属性

Sha*_*s88 61 python

我有一个MyThread课程.我有一个方法样本.我试图从具有相同的对象上下文运行它.请看一下代码:

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()
Run Code Online (Sandbox Code Playgroud)

看起来很简单不是吗.但是当我运行它时,我得到了这个错误

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'
Run Code Online (Sandbox Code Playgroud)

我这样称呼它

arThreads = []
maxThreads = 2;

for i in range( maxThreads ):
    redisOpsObj = redisOps()
    arThreads.append( myThread(i, "Thread-"+str(i), 10, redisOpsObj) )
Run Code Online (Sandbox Code Playgroud)

对不起,我无法发布redisOps类代码.但我可以向你保证,它运作得很好

Ign*_*ams 82

你的缩进是愚蠢的,你混合了标签和空格.运行脚本以python -tt进行验证.

  • @akshay_rahar:`python -tt script.py` (8认同)
  • 请您告诉我“使用 python -tt 运行脚本进行验证”是什么意思? (4认同)
  • 更新:`-tt`标志在Python 3中不存在,在Python 2中存在。 (4认同)

Tim*_*ayi 19

如果您使用的是 python 3+,如果您使用以双下划线开头的私有变量,例如 self.__yourvariable,也可能会发生这种情况。对于可能遇到此问题的一些人,请注意一些事项。

  • 它记录在这里:https://docs.python.org/3/tutorial/classes.html#private-variables (3认同)
  • 刚遇到这个问题就发现了这个评论,为什么他们要这么设计呢? (2认同)

Tre*_*or 11

Python多线程时常见这类错误.所发生的是,在翻译拆除时,相关模块(myThread在这种情况下)经历了一种类型del myThread.

这个电话self.sample()大致相当于myThread.__dict__["sample"](self).但是如果我们在解释器的拆卸序列中,那么它自己的已知类型的字典可能已经被myThread删除了,现在它基本上是NoneType- 而且没有'sample'属性.

  • 我知道我迟到了五年,但你知道这个问题的解决方案吗? (3认同)

Mit*_*dra 8

如果您在类中使用插槽并且尚未在插槽中添加此新属性,也可能会发生这种情况。

class xyz(object):
"""
class description

"""

__slots__ = ['abc', 'ijk']

def __init__(self):
   self.abc = 1
   self.ijk = 2
   self.pqr = 6 # This will throw error 'AttributeError: <name_of_class_object> object has no attribute 'pqr'
Run Code Online (Sandbox Code Playgroud)