How to get a specific class name as a string?

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?

+73
python
Feb 06 '09 at 18:18
source share
3 answers
  instance.__class__.__name__ 

Example:

 >>> class A(): pass >>> a = A() >>> a.__class__.__name__ 'A' 
+130
Feb 06 '09 at 18:20
source share
 <object>.__class__.__name__ 
+10
Feb 06 '09 at 18:23
source share

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

 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 displays a function for each type. transform gets this function and applies it to the parameter.

Of course, it would be much better to use the "real" OOP

+8
Feb 06 '09 at 19:15
source share



All Articles