What kind of class does my instance belong too?

Steve Holden sholden at holdenweb.com
Mon Nov 13 18:29:12 CET 2000

Peter Stöhr wrote:
> Hi out there in the python-universe,
> I'm having a small problem and after looking at the docs I was not able
> to solve it by myself. So maybe someone out there can help me.
> Lets assume I have create a class Spam and a class Eggs derived form
> class Spam.
> In one of the methods I have to implement a behaviours depending on
> whether a passed instance is an instance of class Spam or something
> different, for example:
> class Spam:
>     ...
> class Eggs(Spam):
>     def doSomething(self, aArg):
>         if aArg is instance of Spam:
>             self.spamIt()
>         else:
>             seld.doSoemthingDifferent()
> What I try to figure out is what is the correct way to write such an
> if-statement ?
> I've tried the builtin function type(). The result <type 'instance'> is
> correct bit doesn't solve my problem :-(
> Thanks in advance
>     Peter

>From the 2.0 docs (also available in 1.5.2):

isinstance (object, class) 
   Return true if the object argument is an instance of the class argument,
   or of a (direct or indirect) subclass thereof. Also return true if class
   is a type object and object is an object of that type. If object is not
   a class instance or a object of the given type, the function always
   returns false. If class is neither a class object nor a type object,
   a TypeError exception is raised. 

should give you what you want.

introspective-ly y'rs - steve
Helping people meet their information needs with training and technology.
703 967 0887      sholden at bellatlantic.net      http://www.holdenweb.com/

More information about the Python-list mailing list