Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get the class name of an instance in Python?
In Python object-oriented programming, getting the class name of an instance is a common requirement. Python provides several approaches to retrieve the class name from any object or instance.
Using __class__.__name__
The most straightforward method uses the __class__ attribute combined with __name__ to get the class name ?
class Animal:
def __init__(self, name):
self.name = name
lion = Animal("Lion")
print(lion.__class__.__name__)
Animal
The __class__ attribute returns the class object, while __name__ gives the actual class name as a string.
Example with Built-in Types
# Different data types
text = "Hello Python"
numbers = [1, 2, 3, 4]
data = {"key": "value"}
print(text.__class__.__name__)
print(numbers.__class__.__name__)
print(data.__class__.__name__)
str list dict
Using type() and __name__
The type() function returns the class of an object. Combined with __name__, it provides the class name ?
class Vehicle:
def __init__(self, brand):
self.brand = brand
car = Vehicle("Toyota")
print(type(car).__name__)
# Works with any object
print(type(42).__name__)
print(type(3.14).__name__)
Vehicle int float
Example with Imported Modules
import itertools counter = itertools.count(1) print(type(counter).__name__) # Using datetime from datetime import datetime now = datetime.now() print(type(now).__name__)
count datetime
Using __qualname__ for Nested Classes
For nested classes, __qualname__ provides the fully qualified name, while __name__ only returns the simple class name ?
class Outer:
def __init__(self):
self.inner = self.Inner()
class Inner:
def __init__(self):
self.value = "nested"
obj = Outer()
print(obj.inner.__class__.__name__)
print(obj.inner.__class__.__qualname__)
Inner Outer.Inner
Comparison
| Method | Returns | Best For |
|---|---|---|
obj.__class__.__name__ |
Simple class name | Most common use cases |
type(obj).__name__ |
Simple class name | When working with type objects |
obj.__class__.__qualname__ |
Qualified class name | Nested classes |
Practical Example
class Shape:
def get_info(self):
return f"This is a {self.__class__.__name__}"
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
# Create instances
circle = Circle(5)
rectangle = Rectangle(10, 20)
print(circle.get_info())
print(rectangle.get_info())
This is a Circle This is a Rectangle
Conclusion
Use __class__.__name__ for most cases to get class names. Use type().__name__ when working with type objects, and __qualname__ for nested classes that need fully qualified names.
