[Q] Type checking...

Thomas Wouters thomas at xs4all.nl
Mon Jul 19 08:20:24 EDT 1999


On Mon, Jul 19, 1999 at 01:32:58PM +0200, Klaus Alexander Seistrup wrote:
> Olivier Deckmyn <olivier.deckmyn at mail.dotcom.fr> wrote:

> > Abstract : [Q]How to check the type of an instance before(after?)
> > sending it to a method...

> One possible solution is:

> MAGIC="I'm in class A :-)"

> class ClassA:
>   def __init__(self):
>     self.magic = MAGIC

[etc]

Actually... there is a builtin function 'isinstance':

|>>> class ClassA:
|...     def spam(a):
|...             print a*20
|...
|>>> class ClassB:
|...     def mymethod(self, anInstance):
|...             if isinstance(anInstance, ClassA):
|...                     print "Yes :)"
|...             else:
|...                     print "No :("
|...
|
|>>> b=ClassB()
|>>> a=ClassA
|>>> c="eggs"
|
|>>> b.mymethod(a)
|Yes :)
|>>> b.mymethod(c)
|No :(

|>>> print __builtins__.isinstance.__doc__
|isinstance(object, class-or-type) -> Boolean
|
|Return whether an object is an instance of a class or of a subclass thereof.
|With a type as second argument, return whether that is the object's type.

See, no need to fuzzle with magic, Python does it for you :-) There's also
'issubclass' btw:

|>>> print __builtins__.issubclass.__doc__
|issubclass(C, B) -> Boolean
|
|Return whether class C is a subclass (i.e., a derived class) of class B.

__module__.function.__doc__.rocks()'ly yours,

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list