178k views
3 votes
Write code to check whether the given object belongs
to a class or its subclass?

User Vbezhenar
by
7.6k points

1 Answer

6 votes

Final answer:

To determine if an object belongs to a class or its subclass, use the isinstance() function in Python. This function returns True if the object is an instance of the specified class or its subclass.

Step-by-step explanation:

To check whether a given object belongs to a class or its subclass in a programming language like Python, you would use the built-in isinstance() function. The isinstance() function takes two arguments. The first is the object you are checking, and the second is the class (or a tuple of classes) you want to check against. If the object is an instance of the class, or any subclass thereof, the function returns True; otherwise, it returns False.

Here is a simple code example:

class Parent:
pass

class Child(Parent):
pass

# Create instances
parent_instance = Parent()
child_instance = Child()

# Check instances
class_check = isinstance(child_instance, Parent) # True because Child is a subclass of Parent

print(class_check)

This code defines a parent class and a child class, creates instances of both, and then checks if the child_instance is an instance of the Parent class using isinstance(). The result will be True because Child inherits from Parent.

User Philippe Sillon
by
8.1k points