我目前在PDB跟踪算出这个Python:为什么isinstance返回False,何时应该返回True?
ipdb> isinstance(var, Type)
False
ipdb> type(var)
<class 'module.Type'>
ipdb> Type
<class 'module.Type'>
为什么能这样呢?
P. S. isinstance(var, type(var))
返回True
预期
我目前在PDB跟踪算出这个Python:为什么isinstance返回False,何时应该返回True?
ipdb> isinstance(var, Type)
False
ipdb> type(var)
<class 'module.Type'>
ipdb> Type
<class 'module.Type'>
为什么能这样呢?
P. S. isinstance(var, type(var))
返回True
预期
我只能猜测,但如果你在module
class Type(object): pass
var = Type()
class Type(object): pass
做那么这两种类型的样子<class 'module.Type'>
,但仍然不同。
你可以检查与
print(id(Type), id(var.__class__))
或
print(Type is var.__class__)
注意,这些比较两个OLD-工作,以及新式的类。 对于新式课程,它们相当于print(Type is type(var))
。 但老式课程并非如此。
另一种相当常见的陷阱是,你把这个模块
python -m module
或
python module.py
使得它被称为__main__
模块。如果它以其真实名称导入其他地方,则以该名称以及以不同的名称空间而知。
另一种猜测可能是您正在与ABCs一起工作,或者让该班级有一个__instancecheck__()
方法。
可能有多种类型被称为“类型”(说在不同的时间点)。你能否提供一个证明问题的完整例子? – NPE
你的代码中有没有'import' /'reload'魔法? –
@RomanBodnarchuk,我不这么认为。你能提供这样的魔法的例子吗? – Shark