如果我们有x = type(a)
和x == y
,这是否必然意味着x is y
?
这里有一个反例,但这是一种欺骗:
>>> class BrokenEq(type):
... def __eq__(cls, other):
... return True
...
>>> class A(metaclass=BrokenEq):
... pass
...
>>> a = A()
>>> x = type(a)
>>> x == A, x is A
(True, True)
>>> x == BrokenEq, x is BrokenEq
(True, False)
而我无法创造出这样的反例:
>>> A1 = type('A', (), {})
>>> A2 = type('A', (), {})
>>> a = A1()
>>> x = type(a)
>>> x == A1, x is A1
(True, True)
>>> x == A2, x is A2
(False, False)
澄清我的问题 - 不通过覆盖等号操作符来做一些疯狂的事情,一个类是否可以存在于两个不同的内存位置,或者导入系统是否会阻止这种情况发生?
如果是这样,我们如何演示这种行为 - 例如,使用reload或__import__
进行奇怪的操作?
如果不是,那么这是否由语言保证或在任何地方记录?
结语:
# thing.py
class A:
pass
最后,这是让我明确真正行为的事情(它支持 Blckknght 的回答中所述的主张)。
>>> import sys
>>> from thing import A
>>> a = A()
>>> isinstance(a, A), type(a) == A, type(a) is A
(True, True, True)
>>> del sys.modules['thing']
>>> from thing import A
>>> isinstance(a, A), type(a) == A, type(a) is A
(False, False, False)
所以,虽然使用importlib.reload
的代码可能会通过类身份破坏类型检查,但无论如何它也会破坏isinstance
。