Checking Instances

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:

  • isinstance returns a bool (True/False) value

  • object is the instance to check

  • class is 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.

../../_images/spaceship_scanner.png

Complete the detect_spaceship_type function so that it returns a string containing the type of ship.

Requirements

  • name: detect_spaceship_type

  • parameters: spaceship an instance of one of Spaceship, AttackShip, InfiniteCargoShip

  • returns: 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