Python Program to Get the Class Name of an Instance
Last Updated :
22 Mar, 2023
In this article, we will see How To Get a Class Name of a class instance.
For getting the class name of an instance, we have the following 4 methods that are listed below:
- Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance.
- Use the type() function and __name__ to get the type or class of the Object/Instance.
- Using the decorator to get the type or class of the Object/Instance.
- Using nested classes to get the type or class of the Object/Instance.
Using __class__.__name__ to Get the Class Name of an Instance
__name__ is a special variable in Python. It is a built-in variable that evaluates the name of the current module. Thus, it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with the if statement.
Python3
# this is a class named car
class car:
def parts():
pass
c = car()
# prints the class of the object c
print(c.__class__)
# this prints the name of the class
classes = c.__class__
# prints the name of the class
print(classes.__name__)
Output:
<class '__main__.car'>
car
Using type() and __name__ attribute to Get the Class Name of an Instance
Also, we can also print the type of c (class car) which gives the object of c and __name__ provides the name of the class. __name__ is a built-in variable that evaluates the name of the current module.
Python3
# this is a class named car
class car:
def parts(self):
pass
c = car()
# this prints the class of a c
print(type(c).__name__)
Output:
car
Using a decorator to Get the Class Name of an Instance
Here, we used @property decorator in order to get a name other than a python method. To get more information about @property decorator, please refer to Python Property Decorator. The function which returns the name of the class
Python3
# class for getting the class name
class test:
@property
def cls(self):
return type(self).__name__
a = test()
print(a.cls)
Output:
test
Using nested classes to Get the Class Name of an Instance
In this example, we can obtain the name of the class object by using the __qualname__ attribute rather than the __name__ attribute. The __qualname__ provides a dotted path to the target object's name. When dealing with nested structures, such as when a method is contained within a class, using __qualname__ is beneficial.
Python3
class bike:
def __init__(self, name, b):
self.name = name
self.car = self.car(b)
class car:
def __init__(self, car):
self.car = car
vehicle = bike("orange", ['potatoes'])
print(vehicle.car.__class__.__name__)
print(vehicle.car.__class__.__qualname__)
Output:
car
bike.car
Using the inspect module from the Python Standard Library:
The inspect module provides several functions for inspecting and introspecting Python objects, including the getmembers() function, which can be used to retrieve a list of all the members of an object, including its class name.
Here is an example of how you can use the inspect module to get the class name of an instance:
Python3
import inspect
class MyClass:
pass
obj = MyClass()
members = inspect.getmembers(obj)
class_name = [m[1] for m in members if m[0] == '__class__'][0]
print(class_name.__name__) # Output: 'MyClass'
This approach first imports the inspect module, and then defines a simple class called MyClass. An instance of MyClass is then created, and the getmembers() function is used to retrieve a list of all the members of the object. This list is then filtered to select only the __class__ member, and the class name is extracted from this member using indexing and the __name__ attribute. This approach can be useful if you need to get the class name of an instance in a more general way, and is not limited to just the methods mentioned in the article.
 Using init_subclass() method:
Approach:
 Step 1:Define a base class with the __init_subclass__() method. This method is called every time a subclass is created and can be used to modify the subclass.
Step 2: Define a subclass and inherit from the base class.
Step 3: Create an instance of the subclass.
Step 4: Access the name attribute of the instance.
Python3
class MyBaseClass:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.name = cls.__name__
class MyClass(MyBaseClass):
pass
obj = MyClass()
print(obj.name)
Time Complexity: O(1)
Space Complexity: O(1)
Similar Reads
Python Program to Get the File Name From the File Path
In this article, we will be looking at the program to get the file name from the given file path in the Python programming language. Sometimes during automation, we might need the file name extracted from the file path. Better to have knowledge of:Python OS-modulePython path moduleRegular expression
5 min read
How to Call the main() Function of an Imported Module in Python
We are given an imported module and our task is to call the main() function of that module after importing it in Python. In this article, we will see how to call the main() of an imported module in Python. Call the main() Function of an Imported Module in PythonBelow, are the code methods of how to
3 min read
Python program to print current hour, minute, second and microsecond
In this article, we are going to discuss how to print current hour, minute, second, and microsecond using Python. In order to print hour, minute and microseconds we need to use DateTime module in Python. Methods useddatetime.now().hour(): This method returns the current hour value of the datetime ob
4 min read
How to Call a Method on a Class Without Instantiating it in Python?
In Python programming, classes and methods are like building blocks for organizing our code and making it efficient. Usually, we create instances of classes to access their partsâattributes and methods. But sometimes, we might want to use a class or its methods without actually creating an instance.
3 min read
Python Program to Find and Print Address of Variable
In this article, we are going to see how to find and print the address of the Python variable. It can be done in these ways:Using id() functionUsing addressof() functionUsing hex() functionMethod 1: Find and Print Address of Variable using id()We can get an address using id() function, id() function
2 min read
Python | Using variable outside and inside the class and method
In Python, we can define the variable outside the class, inside the class, and even inside the methods. Let's see, how to use and access these variables throughout the program. Variable defined outside the class: The variables that are defined outside the class can be accessed by any class or any me
3 min read
How to write memory efficient classes in Python?
Memory efficiency is a critical aspect of software development, especially when working with resource-intensive applications. In Python, crafting memory-efficient classes is essential to ensure optimal performance. In this article, we'll explore some different methods to write memory-efficient class
2 min read
Output of Python program | Set 5
Predict the output of the following programs: Program 1: Python def gfgFunction(): "Geeksforgeeks is cool website for boosting up technical skills" return 1 print (gfgFunction.__doc__[17:21]) Output:coolExplanation: There is a docstring defined for this method, by putting a string
3 min read
How To Make a Subclass from a Super Class In Python
In Python, you can create a subclass from a superclass using the class keyword, and by specifying the superclass in parentheses after the subclass name. The subclass inherits attributes and behaviors from the superclass, allowing you to extend or modify its functionality while reusing the existing c
3 min read
Python Class Members
Python, similarly to other object-oriented allows the user to write short and beautiful code by enabling the developer to define classes to create objects. The developer can define the prototype of an object class based on two types of members: Instance membersClass members In the real world, these
6 min read