Checking Instances#
With Python we can check whether an object is an instance of a particular class
using the built in function isinstance(). This function works on classes
that we define ourselves and those provided by Python.
This is useful when we need to check whether an object implements a particular set of methods from a class.
Syntax
isinstance(object, class)
where:
isinstancereturns abool(True/False) valueobjectis the instance to checkclassis the name of the class to check against
Note
isinstance() also works for parent classes of any object!
Example 1
The value 3 is an integer not a float.
print(isinstance(3, int)) # True
print(isinstance(3, float)) # False
Example 2
In this example, the account instance is an instance of both
SavingsAccount and BaseAccount because of the inheritance.
class BaseAccount:
pass
class SavingsAccount(BaseAccount):
pass
account = SavingsAccount()
print(isinstance(account, SavingsAccount))
print(isinstance(account, BaseAccount))
Code Challenge: Spaceship Scanner
There’s a lot of space ship traffic out in the galaxy and it is hard to tell if a ship is a threat. The boffins in the lab have come up with a scanner to tell you what kind of ship is ahead.
Complete the detect_spaceship_type function so that it returns a string containing the type of ship.
Requirements
name:
detect_spaceship_typeparameters:
spaceshipan instance of one ofSpaceship,AttackShip,InfiniteCargoShipreturns: a string, one of the following:
"Standard spaceship""Attack spaceship - WARNING!""Infinite cargo ship, how boring""Unrecognised ship type, maybe it's alien?"when the ship type is unknown
Example
>>> detect_spaceship_type(InfiniteCargoShip())
Infinite cargo ship, how boring
Here is some code for you to start with:
class Spaceship:
pass
class AttackShip:
pass
class InfiniteCargoShip:
pass
def detect_spaceship_type(spaceship):
# COMPLETE ME
print(detect_spaceship_type(InfiniteCargoShip()))
Solution
Solution is locked