In this Python oops program, we will create python class to get class and module name. The program demonstrates how to retrieve the class name and module name of an object in Python.
Create Python class to get class and module name
Steps to solve the program
- The code demonstrates how to get the class name and module name of an object in Python.
- After creating an object obj of the MyClass class, we use the __class__.__name__ attribute to get the name of the class to which obj belongs. This attribute returns a string containing the class name.
- The __module__ attribute, on the other hand, returns the name of the module where the class is defined. In this case, since the code is executed directly without being imported as a module, the __module__ attribute will return “__main__” indicating that the class is defined in the main module.
- By printing the class name and module name, we can observe the names associated with the object obj of the MyClass class.
class MyClass:
pass
obj = MyClass()
print("Class name:", obj.__class__.__name__)
print("Module name:", obj.__module__)
Output:
Class name: MyClass
Module name: __main__