tags:

views:

1999

answers:

3

I want to avoid calling a lot of isinstance() functions, so I'm looking for a way to get the concrete class' name for an instance variable as a string.

Any ideas?

+10  A: 
 instance.__class__.__name__

example:

>>> class A():
    pass
>>> a = A()
>>> a.__class__.__name__
'A'
SilentGhost
+2  A: 
<object>.__class__.__name__
Morendil
+4  A: 

you can also create a dict with the classes themselves as keys, not necessarily the classnames

typefunc={
    int:lambda x: x*2,
    str:lambda s:'(*(%s)*)'%s
}

def transform (param):
    print typefunc[type(param)](param)

transform (1)
>>> 2
transform ("hi")
>>> (*(hi)*)

here typefunc is a dict that maps a function for each type. transform gets that function and applies it to the parameter.

of course, it would be much better to use 'real' OOP

Javier
+1. An 'is' test on the class object itself will be quicker than strings and won't fall over with two different classes called the same thing.
bobince
Sadly, this falls flat on subclasses, but +1 for the hint to "real" OOP and polymorphism.
Torsten Marek