Sobes.tech
Junior — Middle

Is it possible to determine the parent class of an object created from a child class in Python?

sobes.tech AI

Answer from AI

Yes, in Python, you can determine the parent class of an object created from a child class using built-in attributes.

Each object has an attribute __class__, which indicates its class. The class has an attribute __bases__, which contains a tuple of its parent classes.

Example:

class Parent:
    pass

class Child(Parent):
    pass

obj = Child()

# Get the class of the object
cls = obj.__class__

# Get the parent classes
parents = cls.__bases__
print(parents)  # (<class '__main__.Parent'>,)

Thus, you can find out which classes an object inherits from.