Write a function that returns True if the object is an instance of a class that inherited (directly or indirectly) from the specified class ; otherwise False.Prototype: def inherits_from(obj, a_class):You are not allowed to import any module
Question
Write a function that returns True if the object is an instance of a class that inherited (directly or indirectly) from the specified class ; otherwise False.Prototype: def inherits_from(obj, a_class):You are not allowed to import any module
Solution
Sure, here is a Python function that checks if an object is an instance of a class that inherited from a specified class:
def inherits_from(obj, a_class):
if type(obj) is a_class:
return False
elif issubclass(type(obj), a_class):
return True
else:
return False
This function works as follows:
-
It first checks if the type of the object is exactly the same as the specified class. If it is, the function returns False because the object is not an instance of a class that inherited from the specified class, but an instance of the specified class itself.
-
If the type of the object is not exactly the same as the specified class, the function checks if the type of the object is a subclass of the specified class using the
issubclass()function. If it is, the function returns True because the object is an instance of a class that inherited from the specified class. -
If neither of the above conditions is met, the function returns
Similar Questions
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
Write a function that returns True if the object is exactly an instance of the specified class ; otherwise False.Prototype: def is_same_class(obj, a_class):You are not allowed to import any mod
Write a function that returns the list of available attributes and methods of an object:Prototype: def lookup(obj):Returns a list objectYou are not allowed to import any module
Which built-in function can be used to check if an object is an instance of a class or a subclass thereof?
What will be the output of the following code?class A(): def disp(self): print("A disp()")class B(A): pass#Driver's codeobj = B()obj.disp()Options: Pick one correct answer from belowInvalid syntax for inheritanceError because when the object is created, the argument must be passedNothing is printedA disp()
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.