How To Get The Class Of Object

GOAL

To get object name from the object.

Environment

Python 3.8.7

Method

Use special attributes “__class__” of the object.

Example

f = open('test.txt', 'r')

# getting class name
print(f.__class__.__name__) 
#output => TextIOWrapper

# getting the module where the class is defined
print(f.__class__.__module__) 
#output => _io

f.close()

special attributes

Reference: Special Attributes

  • object.__dict__
    • A dictionary or other mapping object used to store an object’s (writable) attributes.
  • instance.__class__
    • The class to which a class instance belongs.
  • class.__bases__
    • The class to which a class instance belongs.
  • class.__bases__
    • The tuple of base classes of a class object.
  • definition.__name__
    • The name of the class, function, method, descriptor, or generator instance.
  • definition.__qualname__
    • The qualified name of the class, function, method, descriptor, or generator instance.
  • class.__mro__
    • This attribute is a tuple of classes that are considered when looking for base classes during method resolution.