How to get the concrete class name as a string?

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

 instance.__class__.__name__

example:

>>> class A():
    pass
>>> a = A()
>>> a.__class__.__name__
'A'

Solution 2 - Python

<object>.__class__.__name__

Solution 3 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser7305View Question on Stackoverflow
Solution 1 - PythonSilentGhostView Answer on Stackoverflow
Solution 2 - PythonMorendilView Answer on Stackoverflow
Solution 3 - PythonJavierView Answer on Stackoverflow