Binary Special Methods#

These methods compare or combine two objects, and typically take self and other as parameters.

Equality Checks - __eq__ and __ne__#

Used by == and !=. These should return a boolean (True or False), indicating whether the two objects are equal or not.

Examples

def __eq__(self, other):
    return self.name == other.name and self.fuel_weight == other.fuel_weight
def __ne__(self, other):
    return not self == other

Order Checks - __lt__, __le__, __gt__, __ge__#

Used by <, <=, >, >=. These methods define ordering and must also return a boolean.

Examples

def __lt__(self, other):
    return self.fuel_weight < other.fuel_weight
def __gt__(self, other):
    return self.rounds > other.rounds

Arithmetic - __add__, __sub__#

Used by + and -. These should return a new object or value that represents the result of the operation.

Examples

def __add__(self, other):
    return self.fuel_weight + other.fuel_weight
def __sub__(self, other):
    return self.fuel_capacity - other.fuel_capacity
Code Challenge: Set Phasers to Equal

Note

For this exercise you should have completed Unary Special Methods > “Identify Yourself! Redux”

Are those the same ships? Who knows? Well, we do.

Complete the Spaceship class with a __eq__ method that checks whether a ship is equal to another ship.

Requirements

  • Ships are considered equal if:

    • they are both instances of Spaceship

    • they have the same name

    • they have the same fuel_capacity

  • Your __eq__ method must always return a bool

Example

>>> xwing = Spaceship("X Wing", 500)
>>> xwing.refuel(500)  # Fill 'er up!
>>> print(xwing == xwing)
True

>>> falcon = Spaceship("Millenium Falcon", 10000)
>>> falcon.refuel(10000)
>>> print(falcon == xwing)
False

Here is some code for you to start with:

class Spaceship:
    def __init__(self, name, fuel_capacity):
        self.name = name
        self.fuel_weight = 0
        self.fuel_capacity = fuel_capacity

    def refuel(self, weight):
        if self.fuel_weight + weight > self.fuel_capacity:
            self.fuel_weight = self.fuel_capacity
        else:
            self.fuel_weight += weight

    def fire_laser(self):
        if self.fuel_weight >= 10:
            self.fuel_weight -= 10

    # YOUR METHODS HERE


xwing = Spaceship("X Wing", 500)
xwing.refuel(500)  # Fill 'er up!

print(xwing == xwing)

falcon = Spaceship("Millenium Falcon", 10000)
falcon.refuel(10000)

print(falcon == xwing)
Solution

Solution is locked

Code Challenge: Sorting the Fleet

Note

For this exercise you should have completed Binary Special Methods > “Set Phasers to Equal”

With so many ships in your fleet its become hard to find the right one to take for a spin. To make the decision easier, lets enable sorting of the fleet by their fuel capacity. That way you can pick a ship appropriate for the distance.

Complete the Spaceship class with __lt__ and __gt__ methods that checks whether a ship is less than or greater than another another ship.

This will allow you to make < , > comparisons and use Python’s built-in sorted function.

Requirements

  • Ships are measured based on their fuel_capacity

  • Your __lt__ and __gt__ methods methods must always return a bool

Example

>>> xwing = Spaceship("X Wing", 500)
>>> xwing.refuel(500)  # Fill 'er up!
>>> print(xwing < xwing)
False

>>> falcon = Spaceship("Millenium Falcon", 1000)
>>> falcon.refuel(10000)
>>> print(xwing > falcon)
False

>>> a = [
...      Spaceship("Enterprise", 10000),
...      Spaceship("X Wing", 500),
...      Spaceship("Millenium Falcon", 1000)
... ]
>>> sorted_ships = list(sorted(ships))
>>> print(sorted_ships)
[X Wing [Fuel: 0/500 (0%)], Millenium Falcon [Fuel: 0/1000 (0%)], Enterprise [Fuel: 0/10000 (0%)]]

Here is some code for you to start with:

class Spaceship:
    def __init__(self, name, fuel_capacity):
        self.name = name
        self.fuel_weight = 0
        self.fuel_capacity = fuel_capacity

    def refuel(self, weight):
        if self.fuel_weight + weight > self.fuel_capacity:
            self.fuel_weight = self.fuel_capacity
        else:
            self.fuel_weight += weight

    def fire_laser(self):
        if self.fuel_weight >= 10:
            self.fuel_weight -= 10

    # YOUR METHODS HERE


xwing = Spaceship("X Wing", 500)
xwing.refuel(500)  # Fill 'er up!

print(xwing < xwing)

falcon = Spaceship("Millenium Falcon", 1000)
falcon.refuel(10000)

print(xwing > falcon)

ships = [
    Spaceship("Enterprise", 10000),
    Spaceship("X Wing", 500),
    Spaceship("Millenium Falcon", 1000)
]

sorted_ships = list(sorted(ships))

print(sorted_ships)
Solution

Solution is locked

Code Challenge: CargoShip Status Report

Note

For this exercise you should have completed Binary Special Methods > “Sorting the Fleet”

The intergalactic parliament is now introducing screening at customs checkpoints throughout the galaxy. As part of this process CargoShips have to report how many items they have on board.

Complete the CargoShip class with __len__ and __str__ and methods. The len method should return how many items are in the cargo hold and the str method must include this information.

Requirements

  • The len of a CargoShip must return the number of items in the cargo list.

  • __str__ must return a string of the form:

{name} [Items {len(cargo)}, Fuel: {fuel_weight}/{fuel_capacity} ({fuel_percent}%)]

See example below.

  • The fuel_percent must be reported to 0 decimal places.

  • The __repr__ method must then use this same format.

Note

You can call str(self) from __repr__ to save time. If you’ve done this for Spaceship you don’t need to write a __repr__ method for CargoShip.

Example

>>> freighter = CargoShip("Galactic Freighter", fuel_capacity=10000)
>>> freighter.refuel(1000)
>>> freighter.load("Turbo Encabulator")
>>> freighter.load("Phase Dectractor")
>>> freighter.load("Cardinal Grammeter")
>>> print(len(freighter))
3

>>> print(freighter)
Galactic Freighter [Items: 3, Fuel: 1000/10000 (10%)]

Here is some code for you to start with:

class Spaceship:
    def __init__(self, name, fuel_capacity):
        self.name = name
        self.fuel_weight = 0
        self.fuel_capacity = fuel_capacity

    def refuel(self, weight):
        if self.fuel_weight + weight > self.fuel_capacity:
            self.fuel_weight = self.fuel_capacity
        else:
            self.fuel_weight += weight

    def fire_laser(self):
        if self.fuel_weight >= 10:
            self.fuel_weight -= 10

    # YOUR METHODS HERE



class CargoShip(Spaceship):
    def __init__(self, name, fuel_capacity):
        super().__init__(name, fuel_capacity)
        self.cargo = []

    def load(self, item):
        self.cargo.append(item)

    def unload(self):
        if self.cargo:
            return self.cargo.pop()
        return None

    # YOUR METHODS HERE



freighter = CargoShip("Galactic Freighter", fuel_capacity=10000)
freighter.refuel(1000)

freighter.load("Turbo Encabulator")
freighter.load("Phase Dectractor")
freighter.load("Cardinal Grammeter")

print(len(freighter))

print(freighter)
Solution

Solution is locked