Which built-in function can be used to check if an object is an instance of a class or a subclass thereof?
Question
Which built-in function can be used to check if an object is an instance of a class or a subclass thereof?
Solution
The built-in function isinstance() can be used to check if an object is an instance of a class or a subclass thereof.
Here is how you can use it:
- Define or identify the object you want to check. For example, let's say we have an object
awhich is an instance of a classA.
class A:
pass
a = A()
-
Define or identify the class you want to check against. In our case, it's class
A. -
Use the
isinstance()function to check if the object is an instance of the class or its subclass. The function takes two arguments: the object and the class. It returnsTrueif the object is an instance of the class or its subclass, andFalseotherwise.
print(isinstance(a, A)) # This will return True
- If you want to check if the object is an instance of a subclass, you can do so by passing the subclass as the second argument to the
isinstance()function.
class B(A):
pass
b = B()
print(isinstance(b, A)) # This will return True because B is a subclass of A
This is how you can use the isinstance() function to check if an object is an instance of a class or a subclass thereof.
Similar Questions
Which function is used to retrieve the class of an instance?
Write a function that returns True if the object is an instance of, or if the object is an instance of a class that inherited from, the specified class ; otherwise False.Prototype: def is_kind_of_class(obj, a_class):You are not allowed to import any module
You have an object and you would like to check to see whether it is an object of a specific class. Which operator would you use?Instruction: Choose the option that best answers the question. Answer Choicesinstancetypeofobjectofinstanceof
Which function is used to retrieve the class of an instance?class()type()isinstance()getattr()
What is an instance of a specific class?
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.