为什么我会收到 AttributeError:对象没有属性? [已关闭]

问题描述 投票:0回答:9

我有一个类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()

看起来很简单是不是。但是当我运行它时,我收到此错误

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 类代码。但我可以向你保证它工作得很好

python python-2.x attributeerror
9个回答
122
投票

你的缩进有问题,并且混合了制表符和空格。使用

python -tt
运行脚本进行验证。


38
投票

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


19
投票

Python 多线程时,此类 bug 很常见。发生的情况是,在解释器拆卸时,相关模块(在本例中为

myThread
)会经历某种
del myThread

调用

self.sample()
大致相当于
myThread.__dict__["sample"](self)
。 但是,如果我们在解释器的拆卸过程中,那么它自己的已知类型字典可能已经被删除了,现在它基本上是一个
myThread
- 并且没有“样本”属性。
    


12
投票
NoneType

时,也可能会发生这种情况。例如:

__slots__

尝试创建实例失败:

class xyz(object): __slots__ = ['abc', 'ijk'] def __init__(self): self.abc = 1 self.ijk = 2 self.pqr = 6



2
投票


1
投票
>>> xyz() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 6, in __init__ AttributeError: 'xyz' object has no attribute 'pqr'

 之类的属性
    


0
投票


0
投票


-3
投票

object._className__attrName.

__updatesoftware 是一个私有方法。

© www.soinside.com 2019 - 2024. All rights reserved.