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.
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.
String is already the name of a class.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With