You can encapsulate classes in a single file, and a file can contain multiple classes. When importing, you can import a single class, multiple classes, or all class from the file.
Example: car.py
"""
A class for representing a car
"""
class Vehicle:
"""A simple attempt to simulate a car"""
def __init__(self, manufacturer, model, year):
"""Initialize attributes"""
self.manufacturer = manufacturer
self.model = model
self.year = year
self.odometer = 0
def get_description(self):
"""Return a neat descriptive message"""
full_name = f"{self.year} {self.manufacturer} {self.model}"
return full_name.title()
def read_odometer(self):
"""Print the car's mileage information"""
print(f"This car has {self.odometer} miles on it")
def update_odometer(self, mileage):
self.odometer = mileage
def increment_odometer(self, miles):
self.odometer += miles
class ElectricVehicle(Vehicle):
"""Unique aspects of an electric car"""
def __init__(self, manufacturer, model, year):
"""Initialize attributes of the parent class"""
super().__init__(manufacturer, model, year)
self.battery_capacity = 70
def describe_battery(self):
print(f"This car has a {self.battery_capacity}-kWh battery.")
def fill_gas_tank(self):
print("This is OK!")
class Battery:
def __init__(self, battery_capacity=70):
"""Initialize battery attributes"""
self.battery_capacity = battery_capacity
def describe_battery(self):
"""Print a message describing the battery capacity"""
print(f"This car has a {self.battery_capacity}-kWh battery.")
def get_range(self):
if self.battery_capacity == 70:
range = 240
elif self.battery_capacity == 85:
range = 270
message = f"This car can go approximately {range} miles on a full charge"
print(message)
Importing Methods
import car- Import the entire modulefrom car import *- Import all classes from the module
When classes are interdependent, be mindful of the import order.
Python Standard Library
The OrderedDict from the collections module can be used to maintain the order of key-value pairs as they were added.
Example: Using OrderedDict
from collections import OrderedDict
favorite_languages = OrderedDict()
favorite_languages['jen'] = 'python'
favorite_languages['sarah'] = 'c'
favorite_languages['edward'] = 'ruby'
favorite_languages['phil'] = 'python'
for name, language in favorite_languages.items():
print(f"{name.title()}'s favorite language is {language.title()}.")
Class Naming Conventions and Coding Style
Use camel case for class names, and use lowercase with underscores for instance and module names. Be cautious with the use of blank lines for better readability.