简体   繁体   中英

Strange type info of an instance of a class in Python OOP

I am trying to determine the type info of an object.

>>> class Class1: pass

>>> obj1=Class1()
>>> type(obj1)
<type 'instance'>

I was expecting the type(obj1) returns 'Class1' . Why it is 'instance' instead? What's the type 'instance' ?

In Python2 if a class doesn't inherits from object (directly or indirectly) then it is treated as an old-style class. And in old-style classes all instances are of type 'instance' .

From docs :

The concept of (old-style) class is unrelated to the concept of type : if x is an instance of an old-style class, then x.__class__ designates the class of x, but type(x) is always <type 'instance'> .

Change you class to inherit from object to make it a new-style class:

class Class1(object): pass

Demo:

>>> class Class1(object): pass

>>> type(Class1())
<class '__main__.Class1'>

It's one of the difference between new-style and classic classes in Python 2.x. Indeed:

The concept of (old-style) class is unrelated to the concept of type: if x is an instance of an old-style class, then x.__class__ designates the class of x , but type(x) is always <type 'instance'> .

You have to use new style classes, by inheriting from object to get the expected type() result.

>>> class C1: pass
...
>>> class C2(object): pass
...
>>> type(C1())
<type 'instance'>
>>> type(C2())
<class '__main__.C2'>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM