Python Refresher

Python in a Weekend - Methods

Add a method to the Car class called age that returns how old the car is.

                class Car:
  pass

my_whip = Car()
my_whip.year = 2005
my_whip.age()
            

Solution

                    from datetime import datetime

class Car:
  def age(self):
    print(datetime.today().year-self.year)

my_whip = Car()
my_whip.year = 2005
my_whip.age()
                

Here's some courses you might like: