smwikipedia
smwikipedia

Reputation: 64205

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'?

Upvotes: 2

Views: 85

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250931

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'>

Upvotes: 4

Maxime Lorant
Maxime Lorant

Reputation: 36151

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'>

Upvotes: 3

Related Questions