Python:isinstance(i,type(i))可以评估为False吗? [英] Python: can isinstance(i, type(i)) evaluate to False?
问题描述
我正在下面的代码中查找something
,以便无论如何isinstance()
之后的检查结果为True
:
I am looking for something
in the following piece of code so that the isinstance()
check afterwards evaluates to True
in any case:
i = WonderfulClass()
classinfo_of_i = something(i)
isinstance(i, classinfo_of_i) # must evaluate to True
如果type
是您的回答,请您解释原因,不胜感激. type
是isinstance
的真正对应物吗?或者,反过来说,您能想到isinstance(i, type(i))
评估为False的情况吗?
If type
is your answer, I'd be grateful if you explained why. Is type
the real counterpart of isinstance
? Or, asked the other way round, can you think of a case where isinstance(i, type(i))
evaluates to False?
This question arose in the context of the simple way to check if the elements of a list or set are single type?, where we have to go through a sequence and check if all the sequence elements are of the same kind. In this context, elements will be compared to each other. This comparison could be based on type
or based on isinstance
.
关于isinstance(object, classinfo)
的相关文档:
如果object参数是classinfo的实例,则返回true 论点
Return true if the object argument is an instance of the classinfo argument
推荐答案
是否键入isinstance的真正对应物?或者反过来说,您能想到isinstance(i,type(i))的计算结果为False的情况吗?" >
我看不到isinstance(i, type(i))
不会返回True
的任何情况.
I can't see any situation where isinstance(i, type(i))
would not return True
.
type()
检查实例中的类型对象并返回该类型对象,因此没有理由使返回的值未能通过isinstance()
检查.
type()
inspects and returns the type object from an instance so there's no reason why the returned value would fail the isinstance()
check.
深入研究cPython的源代码,我们看到代码type()
后面的内容只是返回附加到实例的类型对象:
Digging into the source of cPython, we see that the code behind type()
simply returns the type object attached to the instance:
v = (PyObject *)o->ob_type;
Py_INCREF(v);
return v;
要做的是检查类型是否完全匹配(稍后将继续与继承链中的类进行匹配):
while the first thing that the isintance() code does is check if the types match exactly (it would later move on to match against classes in the chain of inheritance):
int
PyObject_IsInstance(PyObject *inst, PyObject *cls)
{
_Py_IDENTIFIER(__instancecheck__);
PyObject *checker;
/* Quick test for an exact match */
if (Py_TYPE(inst) == (PyTypeObject *)cls)
return 1;
请注意,Py_TYPE
只是返回obj->ob_type
的宏,该宏与type()
的返回值匹配.在Include/object.h 中定义为:
Note that Py_TYPE
is simply a macro that returns obj->ob_type
which matches the return value of type()
. This is defined in Include/object.h as:
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
这篇关于Python:isinstance(i,type(i))可以评估为False吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!