Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the concrete class name as a string? [duplicate]

Tags:

python

People also ask

How do I convert a class name to a String?

Get Class Name Using class. In the GetClassName class, we use ExampleClass. class to get the information of the class. It returns a Class instance of type ExampleClass . Now we can call getSimpleName() using the classNameInstance that will return only the class name as a String.

What is the __ str __ method in Python?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.

Can a class name be String?

String is already the name of a class.

What is __ class __ in Python?

We can also use the __class__ property of the object to find the type or class of the object. __class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'>


 instance.__class__.__name__

example:

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

<object>.__class__.__name__

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