Summary: In this programming example, we will learn different ways to get the class name of the given instance in Python.
Method 1: Using instance.__class__.__name__
instance.__class__
is the reference of the type of instance
.
If we use the __name__
attribute on type reference, we get the name of the class.
Example:
class Car:
def __init__(self, name):
self.name = name
car = Car("Lamborghini")
print(car.__class__.__name__)
Output: Car
Method 2: Using type(instance).__name__
Similar to instance.__class__
, type(instance)
also returns the reference of the type of instance.
So, using the __name__
attribute on the type gives the class name of the instance.
Example:
class Car:
def __init__(self, name):
self.name = name
car = Car("Lamborghini")
print(type(car).__name__)
Output: Car
Method 3: Using __qualname__ instead of __name__
The __qualname__
attribute in Python returns the qualified name of the type.
In most cases, __name__
and __qualname__
gives the same results, but when nested classes are involved the results differ.
Example:
class Car:
def __init__(self, name, engine):
self.name = name
self.engine = self.Engine(engine)
class Engine:
def __init__(self, name):
self.name = name
car = Car("Lamborghini", "V12")
print(car.engine.__class__.__name__)
print(car.engine.__class__.__qualname__)
Output:
Engine
Car.Engine
There are the three ways using which we can get the class name of an instance in Python.