Figuring out an object's type

Justin Sheehy dworkin at ccs.neu.edu
Wed May 10 18:23:36 EDT 2000


"David Allen" <s2mdalle at titan.vcu.edu> writes:

> But types doesn't seem to distinguish between different types
> of user defined classes.  I.e. if I say:
> 
> class Foobar:
> 	pass
> 
> class Baz:
> 	pass
> 
> x = Foobar()
> y = Baz()
> 
> then type(x) == type(y) yeilds 1.  
> 
> Which kinda sucks.  :)
> 
> How do I tell the difference between a Foobar and a Baz? 

Well, there is 'isinstance()':

>>> class Spam:
...     pass
... 
>>> class Eggs:
...     pass
... 
>>> x = Spam()
>>> isinstance(x, Spam)
1
>>> isinstance(x, Eggs)
0

In my own use, however, things like hasattr() are often more useful,
since in Python the name of an instance's class is generally much less
important than the interface that it exposes.

But that depends on what you really want, which you didn't say.

-Justin

 




More information about the Python-list mailing list