1d. Checking Instance Types Flashcards
How do you check what type an object is in Python?
By using the type
function and passing it the instance.
class=Book
object=book
solution=type(book)
output=
How do you compare two objects to see whether they’re the same type?
By using the type
function and comparing the value returned for two different instances.
class1=Book
class2=Newspaper
object1=book
object2=newspaper
solution=type(book) == type(newspaper)
output=False
How do you check whether a given object is the instance of a given class?
By using the isinstance
function.
class=Book
object=book
solution=isinstance(book, Book)
output=True
What does isinstance
return if the first parameter is an object and the second is a parent class to the class that the object is an instance of?
It returns true.
For example, in Python, every class ultimately inherits from the object
class. So, if the second parameter passed into the isinstance
method is the object
class, no matter what the type of the first parameter is, it will return true.