【问题标题】:Interpreter thinks 2 declarations of the same class are different解释器认为同一类的 2 个声明不同
【发布时间】:2016-06-14 22:30:52
【问题描述】:

基本上我有一个这样的项目:

<container-folder>
        |- <folder_1>
               |- <extra_folder>
               |        |- source.py
               |
               |- main.py

在main.py 中我声明了这样一个类:

class ClassOne:
    pass

在main.py 的另一种方法中,我有以下代码:

result = source_function()
if not isinstance(result, ClassOne):
    print "failed!"

在source.py,我定义

import container-folder.folder_1.main
...
def source_function():
    return main.ClassOne()

但是,我仍然打印出"failed!"。在调试器中检查时,我有点奇怪:

result 被标记为类型container-folder.folder_1.main.ClassOne,ClassOne 具有签名main.ClassOne。为什么这两者不相等?

我还注意到,如果我使用其完全限定的类名将代码更改为以下内容:

if not isinstance(result, container-folder.folder_1.main.ClassOne):

我得到了预期的成功。

【问题讨论】:

    标签: python python-2.7 class


    【解决方案1】:

    他们不是同一个班级。这是由于一个怪癖,当您运行 python 模块(即python main.py)时,它会以__main__ 运行。因此,您有 __main__.SomeClass(来自程序的根模块)和 main.SomeClass(来自 source 导入的模块),它们是来自不同模块的不同类。

    要解决您的问题,最好将课程移至另一个模块,并让main 和您的source 从第三个模块导入SomeClass。

    从技术上讲,您也可以从__main__ 导入SomeClass,但随后您会遇到循环依赖的各种棘手问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-21
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      相关资源
      最近更新 更多