__name__to Get the Type or Class of the Object/Instance
__name__Properties to Get the Type or Class of an Object/Instance
A class, just like an object constructor, can be defined as a user-defined prototype that is used to create objects. Classes can be created using the keyword
A class is a data structure, and it can hold both data members and member methods.
This tutorial will discuss the method to get the class name in python.
type() Function and
__name__ to Get the Type or Class of the Object/Instance
type() is a predefined function that can be used in finding the type or class of an object.
__name__ is a special built-in variable that basically gives the name of the current module where it is used. Since python has no
main() function like the other languages like C/C++, Java, and other similar languages, if it is the source file that is executed as the main program, then the interpreter sets the value of
__name__. At the same time, when a file is imported from any other module,
__name__ is then set to that module’s name.
type() function and the
__name__ variable are used to get the type or class of the object in the following code.
class num: def __init__(self, num): self.num = num x = num(1) print (type(x).__name__)
In Python 3, all created classes are new-style classes, while in Python 2, old-style classes might co-exist with the new-style classes. A new-style class is a class that gets inherited from the instance of the object, while old-style or classic classes are the basic classes that existed before python 2.1.
The above method can work only with new-style classes.
__name__ Properties to Get the Type or Class of an Object/Instance
__class__ property can also be used to find the class or type of an object. It basically refers to the class the object was created in.
__name__ can also be used along with
__class__ to get the class of the object.
The following code uses both
__name__ to get the class of an object.
class num: def __init__(self, num): self.num = num x = num(1) print (x.__class__) print (x.__class__.__name__)
<class '__main__.num'> num