Figuring out an object's type

Felix Thibault felixt at dicksonstreet.com
Wed May 10 03:57:28 CEST 2000


At 19:40 5/9/00 -0500, David Allen wrote:
>Hello,
>
>How can a python programmer figure out the type of an object?  I
>read the library reference, and the only helpful thing was the type
>library
>
>from types import *
>type(someObject)
>
>etc.  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? 
>Is there some way each class can have a unique typename, so
>I can do something like:
>
>def someFunction(arg):
>	if type(arg) == SomePredefinedObject:
>		doSomething()
>	elif type(arg) == Foobar:
>		doSomethingElse()
>
>etc.

Besides comparing arg.__class__ to Foobar, you can also use the
isinstance built-in function, which works for classes or types:

>>> class Empty:
	pass
	
	
>>> e = Empty()
>>> isinstance(e, Empty)
1
>>> isinstance([1,2,3], types.ListType)
1

and is true for superclasses, as well...

>>> class HalfEmpty(Empty):
	pass
	
	
>>> h = HalfEmpty()
>>> isinstance(h, Empty)
1

-Felix

>Any help would be appreciated.
>-- 
>David Allen
>http://opop.nols.com/
>
>-- 
>http://www.python.org/mailman/listinfo/python-list
>
>





More information about the Python-list mailing list