Skip to content

Learning Python: Day 26

Setting a default value for an attribute

  • when an instance is created, attributes can be defined without being passed in as parameters but rather in the __init__() method, where they are assigned a default value
  • let’s add an attribute called odomerter_reading that starts with the value of 0
  • we’ll also add a method read_odometer()

class Car:

….def __init__(self, make, model, year):

……..”””Initialize attributes to describe a car.”””

……..self.make = make

……..self.model = model

……..self.year = year

……..self.odometer_reading = 0

….def get_descriptive_name(self):

……..–snip–

….def read_odometer(self):

……..”””Print a statement showing the car’s mileage.”””

……..print(f”This car has {self.odometer_reading} miles on it.”)

my_new_car = Car(‘audi’, ‘a4’, 2024)

print(my_new_car.get_descriptive_name())

my_new_car.read_odometer()

  • when Python calls the __init__() method to create a new instance, it stores the make, model, and year values as attributes
  • new attribute odometer_reading is created and sets its initial value to 0
  • new method read_odometer to read a car’s mileage

2024 Audi A4

This car has 0 miles on it.

  • since cars aren’t usually sold with exactly 0 mileage, we need to change the value of this attribute

End of study session.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *