Figuring out an object's type
felixt at dicksonstreet.com
Wed May 10 03:57:28 CEST 2000
At 19:40 5/9/00 -0500, David Allen wrote:
>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
>from types import *
>etc. But types doesn't seem to distinguish between different types
>of user defined classes. I.e. if I say:
>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:
> if type(arg) == SomePredefinedObject:
> elif type(arg) == Foobar:
Besides comparing arg.__class__ to Foobar, you can also use the
isinstance built-in function, which works for classes or types:
>>> class Empty:
>>> e = Empty()
>>> isinstance(e, Empty)
>>> isinstance([1,2,3], types.ListType)
and is true for superclasses, as well...
>>> class HalfEmpty(Empty):
>>> h = HalfEmpty()
>>> isinstance(h, Empty)
>Any help would be appreciated.
More information about the Python-list