Modifying Attribute Values
- three ways to change an attribute’s values: directly through an instance, set the value through a method, or increment the value through a method
Modifying an attribute’s value directly
- simplest way is directly through an instance
class Car:
….–snip–
my_new_car = Car(‘audi’, ‘a4’, 2024)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
- used dot notation to access the car’s odometer_reading attribute and set its value directly
2024 Audi A4
This car has 23 miles on it.
Modifying an attribute’s value through a method
- can pass the new value to a method that handles the updating internally
class Car:
….–snip–
….def update_odometer(self, mileage):
……..”””Set the odometer reading to the given value.”””
……..self.odometer_reading = mileage
my_new_car = Car(‘audi’, ‘a4’, 2024)
print(my_new_car.get_descriptive_name())
my_new_car.update_odometer(23)
my_new_car.read_odometer()
- addition of update_odometer() to Car is the only modification
- method takes in a mileage value and assigns it to self.odometer_reading
- using my_new_car instance, we call update_odometer() with 23 as an argument
2024 Audi A4
This car has 23 miles on it.
- can extend the method update_odometer() to do additional work each time the odometer reading is modified
class Car:
….–snip–
….def update_odometer(self, mileage):
……..”””
……..Set the odometer reading to the given value.
……..Reject the change if it attempts to roll the odometer back.
……..”””
if mileage > = self.odometer_reading:
…………self.odometer_reading = mileage
……..else:
…………print(“You can’t roll back an odometer!”)
- if value provided for mileage is greater than or equal to the existing mileage, self.odometer_reading, you can update the odometer reading
- this logic prevents rolling back an odometer
Incrementing an attribute’s value through a method
- if you buy a used car and put 100 miles on it between the time of purchase and registration, we’ll want to add an incremental amount
class Car:
….–snip–
….def update_odometer(self, mileage):
……..–snip–
def increment_odometer(self, miles):
……..”””Add the given amount to the odometer reading.”””
……..self.odometer_reading += miles
my_used_car = Car(‘subaru’, ‘outback’, 2019)
print(my_used_car.get_descriptive_name())
my_used_car.update_odometer(23_500)
my_used_car.read_odometer()
my_used_car.increment_odometer(100)
my_used_car.read_odometer()
- new method increment_odometer() takes ina number of miles, and adds the value to self.odometer_reading
- first we created a used car, my_used_car, set its odometer to 23,500 by calling update_odometer() and passing it 23_500
- finally, called increment_odometer() and pass it 100
2019 Subaru Outback
This car has 23500 miles on it.
This car has 23600 miles on it.
- can modify this method to reject negative increments
End of study session.