Python Class Examples

python class tutorial

A class is the basis of all data in Python, everything is an object in Python, and a class is how an object is defined. They are the foundation of object-oriented programming and represent real-world things you want to model in your programs. You use a class to instantiate objects, which are specific instances of a class. If you had a House class, you might create a colonial object, a contemporary object, or a log cabin object from that base class. A class defines the general behavior that an entire category of objects may have as well as the information that can be associated with those objects. Classes can inherit from each other which means you can create a class that extends the functionality of an existing class. This is a very common practice in Object Oriented Python.


How To Create A Class

A class is usually modeled after a Noun. Classes are things. So we might make a class that represents a Person, House, Vehicle, or Animal. These are all common examples to use when learning about classes. For us, we will create a Vehicle class. What information would we associate with a vehicle, and what behavior would it have? A vehicle may have a type, brand, model and so on. This type of information is stored in python variables called attributes. These things also have behaviors. A Vehicle can drive, stop, honk its horn, and so on. Behaviors are contained in functions and a function that is part of a class is called a method.

A Vehicle class

class Vehicle:
    def __init__(self, brand, model, type):
        self.brand = brand
        self.model = model
        self.type = type
        self.gas_tank_size = 14
        self.fuel_level = 0

    def fuel_up(self):
        self.fuel_level = self.gas_tank_size
        print('Gas tank is now full.')

    def drive(self):
        print(f'The {self.model} is now driving.')

Notice that the gas_tank_size holds a Python Number in this case.

Constructing an object

An instance of a class is called an object. It’s created by calling the class itself as if it were a function. The code below passes in three python strings to create a new vehicle object.

vehicle_object = Vehicle('Honda', 'Ridgeline', 'Truck')

Accessing attribute values

print(vehicle_object.brand)
print(vehicle_object.model)
print(vehicle_object.type)
Honda
Ridgeline
Truck

Calling methods

vehicle_object.fuel_up()
vehicle_object.drive()
Gas tank is now full.
The Ridgeline is now driving.

Creating multiple objects

vehicle_object = Vehicle('Honda', 'Ridgeline', 'Truck')
a_subaru = Vehicle('Subaru', 'Forester', 'Crossover')
an_suv = Vehicle('Ford', 'Explorer', 'SUV')

Modifying attribute values

It is possible to update an attribute value directly, or better yet via methods that can get and set attribute values.

Modifying an attribute directly

cool_new_vehicle = Vehicle('Honda', 'Ridgeline', 'Truck')
cool_new_vehicle.fuel_level = 7

Define a method to update an attribute’s value

class Vehicle:
    def __init__(self, brand, model, type):
        self.brand = brand
        self.model = model
        self.type = type
        self.gas_tank_size = 14
        self.fuel_level = 0

    def fuel_up(self):
        self.fuel_level = self.gas_tank_size
        print('Gas tank is now full.')

    def drive(self):
        print(f'The {self.model} is now driving.')

    def update_fuel_level(self, new_level):
        if new_level <= self.gas_tank_size:
            self.fuel_level = new_level
        else:
            print('Exceeded capacity')

Define a method to increment an attribute’s value

class Vehicle:
    def __init__(self, brand, model, type):
        self.brand = brand
        self.model = model
        self.type = type
        self.gas_tank_size = 14
        self.fuel_level = 0

    def fuel_up(self):
        self.fuel_level = self.gas_tank_size
        print('Gas tank is now full.')

    def drive(self):
        print(f'The {self.model} is now driving.')

    def update_fuel_level(self, new_level):
        if new_level <= self.gas_tank_size:
            self.fuel_level = new_level
        else:
            print('Exceeded capacity')

    def get_gas(self, amount):
        if (self.fuel_level + amount <= self.gas_tank_size):
            self.fuel_level += amount
            print('Added fuel.')
        else:
            print('The tank wont hold that much.')

What about private data?

In many languages, there’s a concept of private variables that cannot be accessed from outside of the class definition. Python doesn’t have that feature. If you want your class data to be private, you can follow the convention to use a leading underscore for declaring private variables, functions, methods, and classes in a module. This does not actually enforce privacy, but it does give a hint to anyone reading the code that these items are private and should only be accessed via getter or setter methods.


Class And Object Naming Conventions

In Python, Class names should follow the UpperCaseCamelCase convention. Object names should be written in lowercase with underscores as separators where needed. Module names should be all lower case and when multiple words are needed and underscore should separate them. It is usually preferable to stick to 1-word names if possible for modules.


Class Inheritance

Class inheritance is a fundamental part of object-oriented programming. This allows you to extend your classes by driving properties and methods from parent classes. When one class inherits from another, it automatically has access to all of the attributes and methods of the parent class. You can declare new attributes and methods in the child class, and override attributes and methods of the parent class. To inherit from another class includes the name of the parent class in parentheses when defining the new class. Also, see Composition Over Inheritance.

The __init__() method for a child class

class ElectricVehicle(Vehicle):
    def __init__(self, brand, model, type):
        super().__init__(brand, model, type)
        self.battery_size = 85
        self.charge_level = 0

Adding new methods to a child class

class ElectricVehicle(Vehicle):
    def __init__(self, brand, model, type):
        super().__init__(brand, model, type)
        self.battery_size = 85
        self.charge_level = 0

    def charge(self):
        self.charge_level = 100
        print('The vehicle is now charged.')

    def fuel_up(self):
        print('This vehicle has no fuel tank!')

Using child and parent methods

electric_vehicle = ElectricVehicle('Tesla', 'Model 3', 'Car')
electric_vehicle.charge()
electric_vehicle.drive()

Overriding parent methods

class ElectricVehicle(Vehicle):
    def __init__(self, brand, model, type):
        super().__init__(brand, model, type)
        self.battery_size = 85
        self.charge_level = 0

    def charge(self):
        self.charge_level = 100
        print('The vehicle is now charged.')

    def fuel_up(self):
        print('This vehicle has no fuel tank!')

Instances as attributes

You can store an instance of a class in a different class attribute. This makes it possible for classes to work together to model complex situations.

A Battery class

class Battery:
    def __init__(self, size=85):
        self.size = size
        self.charge_level = 0

    def get_range(self):
        if self.size == 85:
            return 260
        elif self.size == 100:
            return 315

Storing an instance of a class in an attribute

class ElectricVehicle(Vehicle):
    def __init__(self, brand, model, type):
        super().__init__(brand, model, type)
        self.battery = Battery()

    def charge(self):
        self.battery.charge_level = 100

    print('The vehicle is fully charged.')

Using The Instance

electric_vehicle = ElectricVehicle('Tesla', 'CyberTruck', 'Truck')
electric_vehicle.charge()
print(electric_vehicle.battery.get_range())
electric_vehicle.drive()
The vehicle is fully charged.
260
The CyberTruck is now driving.

Importing Classes

Class files grow in size as you add features and functionality. In order to keep your program files uncluttered, you can store your classes in modules and import the classes you need into your main program as needed.

Storing classes in a file

vehicle.py

class Vehicle:
    """Vehicle Class data and methods"""

class Battery:
    """Batter Class data and methods"""

class ElectricVehicle(Vehicle):
    """ElectricVehicle Class data and methods"""

Importing individual classes from a module

vehicle_objects.py

from vehicle import Vehicle, ElectricVehicle
a_mini = Vehicle('Cooper', 'Mini', 'Car')
a_mini.fuel_up()
a_mini.drive()
a_tesla = ElectricVehicle('Tesla', 'Model 3', 'Car')
a_tesla.charge()
a_tesla.drive()

Importing an entire module

import vehicle
a_mini = Vehicle('Cooper', 'Mini', 'Car')
a_mini.fuel_up()
a_mini.drive()
a_tesla = ElectricVehicle('Tesla', 'Model 3', 'Car')
a_tesla.charge()
a_tesla.drive()

Understanding self in Python

You can see that the first parameter of a method is always self. Self is not a keyword, you can actually name that first parameter whatever you like. It does make great sense to use self however, as it is a convention that is recommended you use self so that as people who read your code will know what you’re talking about. So the first argument is self, which is a reference to the object, not the class, to the object. When an object is created from the class, self will reference that object. It provides a way to make other variables and objects available everywhere in a class. The self variable is automatically passed to each method that’s called through an object, which is why it’s listed first in every method definition. Variables attached to self are available everywhere in the class.

Understanding __init__()

The __init__() method is a function that belongs to a class, just like other methods. What is important regarding __init__() is that it’s called automatically every time you instantiate a new object from a class. In other words, it is a constructor function.


Storing objects in a list

Lists can hold as few or as many things as you want them to. In addition to all the other types you can store in a list, objects can be stored in lists as well. Let’s see a few examples of how this works. Here’s an example showing how to instantiate a group of rental vehicles, and ensure all the vehicles are ready to drive.

A collection of rental vehicles

from vehicle import Vehicle, ElectricVehicle
gas_fleet = []
electric_fleet = []

for _ in range(100):
    vehicle = Vehicle('Honda', 'Civic', 'Car')
    gas_fleet.append(vehicle)
for _ in range(50):
    evehicle = ElectricVehicle('Nissan', 'Leaf', 'Car')
    electric_fleet.append(evehicle)
for vehicle in gas_fleet:
    vehicle.fuel_up()
for evehicle in electric_fleet:
    evehicle.charge()
print(f'Gas vehicles: {len(gas_fleet)}')
print(f'Electric vehicles: {len(electric_fleet)}')

Learn More About Python Classes

Python Class Examples Summary

If you want to do object-oriented programming in Python, then you need a good understanding of how Classes work. In this collection of python class examples, we had a look at what classes are, how to create and use a class, what instance attributes are, how to modify attributes, how to use inheritance, and how to follow proper naming conventions.