Working with classes and instances
- after writing a class, most time is spent working with instances
- like modifying attributes associated with instances directly or by writing methods that update attributes in specific ways
The car class
- car class will store info about the kind of car we’re working with
- will have a method that summarizes this info
car.py
class Car:
….”””A simple attempt to represent a car.”””
def __init__(self, make, model, year):
….”””Initialize attributes to describe a car.”””
….self.make = make
….self.model = model
….self.year = year
def get_descriptive_name(self):
….”””Return a neatly formatted descriptive name.”””
….long_name = f”{self.year} {self.make} {self.model}”
….return long_name.title()
my_new_car = Car(‘audi’, ‘a4’, 2024)
print(my_new_car.get_descriptive_name())
- need to specify a make, model, and year for our instance when making a new Car instance
- defined a method called get_descriptive_name() that puts a car’s info into one string, don’t need to print each attribute’s value individually
- use self.make, self.model, and self.year to work with attribute values in this method
- make an instance from the Car class and assign it to the variable my_new_car
2024 Audi A4
- next, we’ll add an attribute that stores the car’s mileage
End of study session.