Saturday, November 16, 2024
Google search engine
HomeLanguagesPython Program to Get the Class Name of an Instance

Python Program to Get the Class Name of an Instance

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'


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)


Output

MyClass

Time Complexity: O(1)
Space Complexity: O(1)

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments