How to get the concrete class name as a string?

Question:

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?

Asked By: user7305

||

Answers:

 instance.__class__.__name__

example:

>>> class A():
    pass
>>> a = A()
>>> a.__class__.__name__
'A'
Answered By: SilentGhost
<object>.__class__.__name__
Answered By: Morendil

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

Answered By: Javier
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.