167

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?

hochl
  • 11,784
  • 10
  • 53
  • 83
user7305
  • 5,413
  • 9
  • 27
  • 23
  • 2
    This is NOT a duplicate of a question that got me here. I'm reading the "Concrete Objects Layer" documentation for Python 3. That documentation describes C-level mappings with types that are lower-level than the regular class name. So, for example, the documentation describes a "PyLongObject". I'd like to know how to get this low-level name given an arbitrary object. – Tom Stambaugh Jun 17 '18 at 18:59

3 Answers3

289
 instance.__class__.__name__

example:

>>> class A():
    pass
>>> a = A()
>>> a.__class__.__name__
'A'
SilentGhost
  • 287,765
  • 61
  • 300
  • 288
24
<object>.__class__.__name__
Morendil
  • 3,818
  • 18
  • 22
9

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
  • 58,927
  • 8
  • 76
  • 126
  • +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 Feb 06 '09 at 19:19
  • Sadly, this falls flat on subclasses, but +1 for the hint to "real" OOP and polymorphism. – Torsten Marek Feb 06 '09 at 19:25