Object oriented programming

Using an object

Below is the definition of an object. Run the cell and create at least two instances of it.


In [ ]:
class Car:
    
    def __init__(self, make, model, year, mpg=25, tank_capacity=30.0, miles=0):
        self.make = make
        self.model = model
        self.year = year
        self.mpg = mpg
        self.gallons_in_tank = tank_capacity # cars start with a full tank
        self.tank_capacity = tank_capacity
        self.miles = miles
        
    def __str__(self):
        return "{} {} ({}), {} miles and {} gallons in tank".format(self.make, 
                                                                    self.model, 
                                                                    self.year, 
                                                                    self.miles, 
                                                                    self.gallons_in_tank)
    
    def drive(self, new_miles):
        """Drive the car X miles and return number of miles driven.
        If there is not enough fuel, drive 0 miles."""
        fuel_need = new_miles/self.mpg
        if fuel_need <= self.gallons_in_tank:
            self.miles = self.miles + new_miles
            self.gallons_in_tank = self.gallons_in_tank - fuel_need
            return new_miles
        else:
            return 0

In [ ]:

Simple modification to class

OK, our car has a major problem: it can't be filled up.

Add a method called fill_up() to your class. It is up to you if you want to enable filling by an arbitary number or only back to the full state.

If you allow arbitary amounts of liquid remember to consider overfilling the tank.

Once you edit your class, the old objects do not automatically adopt to the changes you made. You will need to re-create them.

Exceptions

Now make a modification to the drive-method: if an attempt is made to drive more than the gas will allow, create and raise an exception.

Instead of creating your own exception you may use a ValueError for this case, as it is a logical choice.

Then add a try-except clause to the following:


In [ ]:
suv = Car("Ford", "Escape", 2017, mpg=18, tank_capacity=30)
suv.drive(600)

Bonus exercises

Magic methods

Create a class called element for storing the following data

  • name
  • symbol
  • atomic number
  • molecular weight

You can use the following data for creating instances of a few elements:

Element symbol atomic number molecular weight
Hydrogen H 1 1.01
Iron Fe 26 55.85
Silver Ag 47 107.87

In [ ]:

Next, we would like to be able to sort elements according to their atomic number. In order to do this, let's implement magic methods __lt__ and __eq__ as described here.

Once finished, store few instances of a elements in a list, and try to sort it using list's sort method.


In [ ]: