QuantumFool
QuantumFool

Reputation: 609

Determine the type of a (not built in) class in python

I've got a grid representing a tessellation, which is a set of instances of the Polygon class (a class I made). I also have a Boundary class, which is the class representing the boundary of the simulation I'm running (another class I've made). Any line of any pentagon can either have two Polygon objects or a Polygon and a Boundary object as "parents" (an attribute which I've defined for the line class). The type of the object determines how I do certain computations.

So, in short, I need a way to tell which of two classes a particular variable is an instance of, where I've made both classes. When I call type(parent), I get:

 <type 'instance'>

How am I supposed to determine this?

Upvotes: 0

Views: 1096

Answers (3)

Malik Brahimi
Malik Brahimi

Reputation: 16721

Try testing the __class__ attribute of your object:

class Class(object):
    def __init__(self):
        pass # Object created

obj = Class()
print obj.__class__ == Class

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251126

In old-style classes you check the class of an instance using its __class__ attribute, in new-style classes type() will work fine(Read: NewClass Vs Classic Class). In old-style classes every instance of user-defined class was of type instance(Unifying types and classes in Python 2.2).

>>> a = A()
>>> class A:
    pass
... 
>>> a = A()
>>> a.__class__
<class __main__.A at 0x7fcce57b1598>
>>> a.__class__ is A
True

In new-style classes type(ins) and ins.__class__ now do the same thing:

>>> class B(object): # Inherit from object to create new-style class
    pass
... 
>>> b = B()
>>> type(b)
<class '__main__.B'>
>>> b.__class__
<class '__main__.B'>

You can also use isinstance() to check if an object is an instance of a class:

>>> isinstance(a, A)
True
>>> isinstance(b, B)
True

But checking this using isinstance doesn't mean the class is the exact parent of the instance:

>>> class C(B):
    pass
... 
>>> c = C()
>>> isinstance(c, B)
True

Upvotes: 0

user2555451
user2555451

Reputation:

The idiomatic way to perform typechecking in Python is to use isinstance:

if isinstance(x, Boundary):
    # x is of type Boundary
elif isinstance(x, Polygon):
    # x is of type Polygon

Demo:

>>> class Boundary:
...     pass
...
>>> x = Boundary()
>>> isinstance(x, Boundary)
True
>>>

Note that doing type(x) is Boundary would also work, but it will not factor in inheritance like isinstance does.

Upvotes: 3

Related Questions