0% found this document useful (0 votes)
26 views2 pages

Beginners Python Cheat Sheet PCC Classes BW

Uploaded by

amkslade101
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)
26 views2 pages

Beginners Python Cheat Sheet PCC Classes BW

Uploaded by

amkslade101
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
You are on page 1/ 2

Beginner's Python

Creating and using a class (cont.) Class inheritance


Creating an instance from a class If the class you're writing is a specialized version of another
class, you can use inheritance. When one class inherits

Cheat Sheet - Classes


my_car = Car('audi', 'a4', 2021)
from another, it automatically takes on all the attributes
Accessing attribute values and methods of the parent class. The child class is free
to introduce new attributes and methods, and override
print(my_car.make)
attributes and methods of the parent class.
print(my_car.model)
What are classes? print(my_car.year)
To inherit from another class include the name of the
parent class in parentheses when defining the new class.
Classes are the foundation of object-oriented
Calling methods The __init__() method for a child class
programming. Classes represent real-world things
you want to model in your programs such as dogs, my_car.fill_tank() class ElectricCar(Car):
cars, and robots. You use a class to make objects, my_car.drive() """A simple model of an electric car."""
which are specific instances of dogs, cars, and robots. Creating multiple instances
A class defines the general behavior that a whole def __init__(self, make, model, year):
my_car = Car('audi', 'a4', 2024) """Initialize an electric car."""
category of objects can have, and the information that my_old_car = Car('subaru', 'outback', 2018) super().__init__(make, model, year)
can be associated with those objects. my_truck = Car('toyota', 'tacoma', 2020)
Classes can inherit from each other—you can write my_old_truck = Car('ford', 'ranger', 1999) # Attributes specific to electric cars.
a class that extends the functionality of an existing # Battery capacity in kWh.
class. This allows you to code efficiently for a wide Modifying attributes self.battery_size = 40
variety of situations. Even if you don't write many You can modify an attribute's value directly, or you can
# Charge level in %.
of your own classes, you'll frequently find yourself write methods that manage updating values more carefully.
self.charge_level = 0
working with classes that others have written. Methods like these can help validate the kinds of changes
that are being made to an attribute. Adding new methods to the child class
Creating and using a class Modifying an attribute directly class ElectricCar(Car):
Consider how we might model a car. What information would --snip--
my_new_car = Car('audi', 'a4', 2024)
we associate with a car, and what behavior would it have?
my_new_car.fuel_level = 5
The information is assigned to variables called attributes, def charge(self):
and the behavior is represented by functions. Functions that Writing a method to update an attribute's value """Fully charge the vehicle."""
are part of a class are called methods. self.charge_level = 100
def update_fuel_level(self, new_level):
print("The vehicle is fully charged.")
The Car class """Update the fuel level."""
if new_level <= self.fuel_capacity: Using child methods and parent methods
class Car:
self.fuel_level = new_level
"""A simple attempt to model a car.""" my_ecar = ElectricCar('nissan', 'leaf', 2024)
else:
print("The tank can't hold that much!")
def __init__(self, make, model, year): my_ecar.charge()
"""Initialize car attributes.""" Writing a method to increment an attribute's value my_ecar.drive()
self.make = make
self.model = model def add_fuel(self, amount):
self.year = year """Add fuel to the tank.""" Finding your workflow
if (self.fuel_level + amount There are many ways to model real world objects and
# Fuel capacity and level in gallons. <= self.fuel_capacity): situations in code, and sometimes that variety can feel
self.fuel_capacity = 15 self.fuel_level += amount overwhelming. Pick an approach and try it; if your first
self.fuel_level = 0 print("Added fuel.") attempt doesn't work, try a different approach.
else:
def fill_tank(self): print("The tank won't hold that much.")
"""Fill gas tank to capacity."""
self.fuel_level = self.fuel_capacity Naming conventions Python Crash Course
print("Fuel tank is full.") In Python class names are usually written in CamelCase A Hands-on, Project-Based
and object names are written in lowercase with underscores. Introduction to Programming
def drive(self): Modules that contain classes should be named in lowercase
"""Simulate driving.""" with underscores. ehmatthes.github.io/pcc_3e
print("The car is moving.")
Class inheritance (cont.) Importing classes Storing objects in a list
Overriding parent methods Class files can get long as you add detailed information and A list can hold as many items as you want, so you can make
functionality. To help keep your program files uncluttered, a large number of objects from a class and store them in a
class ElectricCar(Car):
you can store your classes in modules and import the list.
--snip--
classes you need into your main program. Here's an example showing how to make a fleet of rental
cars, and make sure all the cars are ready to drive.
def fill_tank(self): Storing classes in a file
"""Display an error message.""" car.py A fleet of rental cars
print("This car has no fuel tank!")
"""Represent gas and electric cars.""" from car import Car, ElectricCar

Instances as attributes class Car: # Make lists to hold a fleet of cars.


A class can have objects as attributes. This allows classes to """A simple attempt to model a car.""" gas_fleet = []
work together to model more complex real-world things and --snip— electric_fleet = []
concepts.
class Battery: # Make 250 gas cars and 500 electric cars.
A Battery class """A battery for an electric car.""" for _ in range(250):
class Battery: --snip-- car = Car('ford', 'escape', 2024)
"""A battery for an electric car.""" gas_fleet.append(car)
class ElectricCar(Car): for _ in range(500):
def __init__(self, size=85): """A simple model of an electric car.""" ecar = ElectricCar('nissan', 'leaf', 2024)
"""Initialize battery attributes.""" --snip-- electric_fleet.append(ecar)
# Capacity in kWh, charge level in %.
Importing individual classes from a module # Fill the gas cars, and charge electric cars.
self.size = size
my_cars.py for car in gas_fleet:
self.charge_level = 0
from car import Car, ElectricCar car.fill_tank()
def get_range(self): for ecar in electric_fleet:
"""Return the battery's range.""" my_beetle = Car('volkswagen', 'beetle', 2021) ecar.charge()
if self.size == 40: my_beetle.fill_tank()
return 150 my_beetle.drive() print(f"Gas cars: {len(gas_fleet)}")
elif self.size == 65: print(f"Electric cars: {len(electric_fleet)}")
return 225 my_leaf = ElectricCar('nissan', 'leaf', 2024)
Using an instance as an attribute
my_leaf.charge() Understanding self
my_leaf.drive()
People often ask what the self variable represents. The
class ElectricCar(Car): self variable is a reference to an object that's been created
--snip--
Importing an entire module
from the class.
import car The self variable provides a way to make other variables
def __init__(self, make, model, year):
and objects available everywhere in a class. The self
"""Initialize an electric car.""" my_beetle = car.Car(
variable is automatically passed to each method that's
super().__init__(make, model, year) 'volkswagen', 'beetle', 2021)
my_beetle.fill_tank() called through an object, which is why you see it listed first
# Attribute specific to electric cars. my_beetle.drive() in most method definitions. Any variable attached to self is
self.battery = Battery() available everywhere in the class.
my_leaf = car.ElectricCar('nissan', 'leaf',
def charge(self): 2024) Understanding __init__()
"""Fully charge the vehicle.""" my_leaf.charge() The __init__() method is a function that's part of a class,
self.battery.charge_level = 100 my_leaf.drive() just like any other method. The only special thing about
print("The vehicle is fully charged.") __init__() is that it's called automatically every time
Importing all classes from a module
Using the instance (Don’t do this, but recognize it when you see it.) you make a new instance from a class. If you accidentally
misspell __init__(), the method won't be called and your
my_ecar = ElectricCar('nissan', 'leaf', 2024) from car import * object may not be created correctly.
my_ecar.charge() my_beetle = Car('volkswagen', 'beetle', 2021)
print(my_ecar.battery.get_range()) my_leaf = ElectricCar('nissan', 'leaf', 2024)
my_ecar.drive() Weekly posts about all things Python
mostlypython.substack.com

You might also like