Extension: Container Methods#
These allow custom objects to behave like collections or sequences (e.g. lists, dicts).
__getitem__#
Used when you access an item by index or key (obj[key]).
def __getitem__(self, index):
return self.cargo[index]
__iter__#
Allow iteration using for item in obj.
def __iter__(self):
return iter(self.cargo)
Code Challenge: CargoShip Items
Note
The intergalactic parliament is now upping the customs screen and demands to look at every item on board.
Complete the CargoShip class with __getitem__ and __iter__ and methods to enable use of ship[idx] and for item in ship.
Requirements
__getitem__must return the item at the given index__iter__must return aniterableover the cargo items in the normal order
Note
You can return Python’s built in iter on the cargo items
Example
>>> freighter = CargoShip("Galactic Freighter", fuel_capacity=10000)
>>> freighter.refuel(1000)
>>> freighter.load("Turbo Encabulator")
>>> freighter.load("Phase Dectractor")
>>> freighter.load("Cardinal Grammeter")
>>> print(freighter[1])
Phase Dectractor
>>> for item in freighter:
... print(item)
Turbo Encabulator
Phase Dectractor
Cardinal Grammeter
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