0% found this document useful (0 votes)
5 views1 page

Importing Car Class in Python Module

Uploaded by

darkflux514
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views1 page

Importing Car Class in Python Module

Uploaded by

darkflux514
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Importing a Single Class

Let’s create a module containing just the Car class. This brings up a subtle
naming issue: we already have a file named [Link] in this chapter, but this
module should be named [Link] because it contains code representing a car.
We’ll resolve this naming issue by storing the Car class in a module named
[Link], replacing the [Link] file we were previously using. From now on, any
program that uses this module will need a more specific filename, such as
my_car.py. Here’s [Link] with just the code from the class Car:

[Link] 1 """A class that can be used to represent a car."""

class Car:
"""A simple attempt to represent a car."""

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


"""Initialize attributes to describe a car."""
[Link] = make
[Link] = model
[Link] = year
self.odometer_reading = 0

def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = f"{[Link]} {[Link]} {[Link]}"
return long_name.title()

def read_odometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometer_reading} miles on it.")

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!")

def increment_odometer(self, miles):


"""Add the given amount to the odometer reading."""
self.odometer_reading += miles

We include a module-level docstring that briefly describes the contents


of this module 1. You should write a docstring for each module you create.
Now we make a separate file called my_car.py. This file will import the
Car class and then create an instance from that class:

my_car.py 1 from car import Car

my_new_car = Car('audi', 'a4', 2024)


print(my_new_car.get_descriptive_name())

174 Chapter 9

You might also like