python - AttributeError: 'module' object has no attribute 'lock'

python - AttributeError: 'module' object has no attribute 'lock'

作为我的单元测试过程的一部分,我正在评估从某个方法返回的变量的类型。方法 returns 一个 'thread.lock' 类型的变量,我想用与测试 'str' 或 'int' 等类型的变量相同的方式来测试它

This is the example carried out in the python 2.7.6 shell

>>> import threading, thread
>>> mylock = threading.Lock()
>>> type(mylock)
<type 'thread.lock'>
>>> type(mylock) is thread.lock

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    type(mylock) is thread.lock
AttributeError: 'module' object has no attribute 'lock'

I expected it to return True as shown in the second example

>>> myint = 4
>>> type(myint)
<type 'int'>
>>> type(myint) is int
True
>>> 

请提供有关如何解决此问题的任何解决方案,我们将不胜感激。谢谢

而不是 thread.lock 使用 thread.LockType:

>>> import threading, thread
>>> mylock = threading.Lock()
>>> type(mylock)
<type 'thread.lock'>
>>> thread.LockType
<type 'thread.lock'>
>>> type(mylock) is thread.LockType
True

但最好使用isinstance():

>>> isinstance(mylock, thread.LockType)
True

改用 isinstance() 函数。

>>> import threading, thread
>>> mylock = threading.Lock()
>>> type(mylock)
<type 'thread.lock'>
>>> isinstance(mylock, type(threading.Lock()))
True