Saturday, January 4, 2025

How to check class of another child class in python


In Python, you can use the isinstance() function to check if an object is an instance of a specific class or any class derived from it. You can also use the issubclass() function to check if a class is a subclass of another class.

 

class Parent:
pass

class Child(Parent):
pass

class Grandchild(Child):
pass

# Creating instances
p = Parent()
c = Child()
g = Grandchild()

# Checking instances
print(isinstance(c, Parent)) # Output: True, because Child is a subclass of Parent
print(isinstance(g, Child)) # Output: True, because Grandchild is a subclass of Child
print(isinstance(g, Parent)) # Output: True, because Grandchild is a subclass of Parent

# Checking subclasses
print(issubclass(Child, Parent)) # Output: True
print(issubclass(Grandchild, Parent)) # Output: True
print(issubclass(Grandchild, Child)) # Output: True
print(issubclass(Parent, Child)) # Output: False
  • isinstance(object, classinfo) returns True if object is an instance of classinfo or a subclass thereof.

  • issubclass(class, classinfo) returns True if class is a subclass of classinfo.

These functions are handy for ensuring your objects and classes inherit from the expected parent classes. 

 

 isinstance(object, class):

    • Checks if the object is an instance of the given class or its subclass.
    • Useful when you have an object and want to verify its type.
  • issubclass(subclass, class):

    • Checks if the given class is a subclass of another class.
    • Useful when you’re dealing with class relationships and not specific instances.

     

    If you want to check if an object belongs to a child class (and not the parent class directly):

    if isinstance(c, Parent) and not isinstance(g, Child):
        print("Object belongs to ChildA but not Parent directly.")

    False

     

  • No comments:

    Post a Comment