Why type(classInstance) is returning 'instance'?

淺唱寂寞╮ 提交于 2019-12-05 01:16:58

Old-style classes do that. Derive your classes from object in their definitions.

you should really use isinstance:

In [26]: def foo(param):
   ....:     print type(param)
   ....:     print isinstance(param, Class1)
   ....:

In [27]: foo(x)
<type 'instance'>
True

Type is better for built-in types.

The fact that type(x) returns the same type object for all instances x of legacy, aka old-style, classes, is one of many infuriating defects of those kinds of classes -- unfortunately they have to stay (and be the default for a class without base) in Python 2.* for reasons of backwards compatibility.

Nevertheless, don't use old-style classes unless you're forced to maintain a bunch of old, legacy code (without a good test suite to give you the confidence to try and switch kind o classes). When a class has no "natural" bases, subclass it from object rather than from nothing. Alternatively, your module, at the top, can set

__metaclass__ = type

which changes the default from the crufty, legacy old-style classes, to the shiny bright new-style ones -- while explicitly inheriting from object is usually preferred ("explicit is better than implicit"), the module-global setting of __metaclass__ may feel "less invasive" to existing old modules where you're switching from old to new classes, so it's offered as a possibility.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!