我的 class 在我的代码开头是可调用的,但在我的测试循环时不可调用

My class is callable at the begining of my code, but not while my tests loops

我有 2 个文件:main.py 和 batsol.py

batsol.py 包含一个 class 并且 main.py 正在从 class Batsol 创建一些实例。 因此,我将向您展示我的代码的简明版本...

class Batsol:
  def __init__(self, addressCan = None, name = None) :
    self.addressCan = addressCan
    self.name = name
    #other stuff ...

然后我的 main.py :

from batsol import Batsol
# other import and code ...

print(callable(Batsol))
bs1 = Batsol()
# code...
if len(listener.ring_buffer) == 0 :
    for Batsol in tab_BS :
        try:
            print(tab_BS[Batsol])
        except (IndexError):
            pass
# code...
while(True) :
  # for and if interlocked
    print(callable(Batsol))
    bs2 = Batsol()

控制台显示:

True
False
Traceback (most recent call last):
File "./main.py", line 135, in <module>
bs2 = Batsol()
TypeError: 'int' object is not callable

回溯的第二部分没有链接到我在我的代码中做的其他事情(线程没有正确终止......类似这样),在我看来

Exception ignored in: <module 'threading' from '/usr/lib/python3.4/threading.py'>
Traceback (most recent call last):
File "/usr/lib/python3.4/threading.py", line 1292, in _shutdown
t = _pickSomeNonDaemonThread()
File "/usr/lib/python3.4/threading.py", line 1300, in _pickSomeNonDaemonThread
if not t.daemon and t.is_alive():
TypeError: 'bool' object is not callable

为什么我的对象在我的测试循环中不可调用??? 这让我发疯...

您的阴影出现在此代码片段中:

if len(listener.ring_buffer) == 0 :
    for Batsol in tab_BS :
        try:
            print(tab_BS[Batsol])
        except (IndexError):
            pass
time.sleep(4)

for-in 构建序列的工作方式如下:

  1. 下一个(第一个、第二个……最后一个)元素需要序列。内部指针跟踪当前迭代中的元素。
  2. 元素被分配给 "in" 左侧的名称。
  3. 转到 1。

循环结束后,Batsol 不再是您的 class,而是来自 tab_BS 的最后一个元素。

我建议获得更好的 IDE,或使用好的静态代码分析工具(Pylint / Flake8 等),因为这种错误很容易被检测到,例如PyCharm(您的代码 隐藏了外部作用域中的名称 )。

相关:How bad is shadowing names defined in outer scopes?