Skip to content
Shop

CommunityJoin Our PatreonDonate

Sponsored Ads

Sponsored Ads

Classes

Let's explore the beauty of classes, where we can group together functions and data together to represent real-world objects.

Brian Long
Senior Developer

What is a class?

A class is group of related data & functions that represent an intangible or real-world object.

Let's say you had a class called Vehicle. The Vehicle class defines everything a vehicle needs to be a vehicle, like doors, wheels, an engine, etc. These parts of the vehicle are the data (or properties) of the class.

Now, the class doesn't actually make a vehicle. It just tells you how to make one. To make a real vehicle, you use the class to create a specific vehicle, like a red sedan or a blue truck. The actual vehicle is called an instance of the Vehicle class.

The things a vehicle can do, like start, stop, accelerate, or turn, are the functions (or methods) of the Vehicle class. These are the actions you can perform with a vehicle.

So, the Vehicle class is the general idea of a vehicle, and each individual vehicle you see on the road is an instance of that class.

python
class Vehicle():
    def __init__(self):
        self.doors = 4
        self.wheels = 4
        self.has_an_engine = True
        self.color = ""
        self.type = ""
    def start(self):
        pass
    def stop(self):
        pass
    def accelerate():
        pass
    def turn(self):
        pass

nissan = Vehicle()
nissan.color = "red"
nissan.type = "sedan"
nissan.start()
nissan.stop()

dodge = Vehicle()
dodge.color = "blue"
dodge.type = "truck"
dodge.start()
dodge.accelerate()

As another example, let's imagine you were making a video game. For your game you might have a player that can do several things like jump() walk() and crouch(). The player may also have variables like speed and acceleration Since these functions and data are related, we could group them together in a class called Player(). Every new player would be able to jump, walk and crouch and have speed and acceleration. The variables player1 and player2 would be instances of the Player class. Note that each instance of the class doesn't change the class itself.

python
class Player():
    def __init__(self):
        self.speed = 0
        self.acceleration = 0
    def jump():
        print("You are jumping")
    def walk():
        print("You are walking")
    def crouch():
        print("You are crouch")

player1 = Player()
player2 = Player()

Note

  • The __init__ function is called an initializer method and it gets called whenever a new player is created. This is typically where you set default values for variables in the class. self refers to the object being created and allows you to manipulate the object itself.

When to use a class?

You should use a class when you have lots of data and several related functions that manipulate that data. This helps minimize the length of your code as well as allows you to re-use large portions of your code without having to re-write it over and over.

python
class Math:
    def add(self, a,b):
        return a + b
    
    def subtract(self, a,b):
        return a - b
    
    def multiply(self, a,b):
        return a * b
    
    def divide(self, a,b):
        return a / b
    
    def remainder(self, a,b):
        return a % b
    
    def exponent(self, a,b):
        return a ** b

mathStudent1 = Math()

print(mathStudent.add(360.00,180.9))
print(mathStudent.subtract(300,120.4))
print(mathStudent.multiply(3,3))
print(mathStudent.divide(365,12))
print(mathStudent.remainder(3,2))
print(mathStudent.exponent(2,3))

mathStudent2 = Math()

print(mathStudent2.add(360.00,180.9))
print(mathStudent2.subtract(300,120.4))
print(mathStudent2.multiply(3,3))
print(mathStudent2.divide(365,12))
print(mathStudent2.remainder(3,2))
print(mathStudent2.exponent(2,3))

@classmethod

In Python, we can use class methods so that we don't have to create instances of the class to use a method in the class. We do so by decorating the method we want to use with the @classmethod decorator.

python
class Math:
    @classmethod
    def add(cls, a,b):
        return a + b
    
    @classmethod
    def subtract(cls, a,b):
        return a - b
    
    @classmethod
    def multiply(cls, a,b):
        return a * b
    
    @classmethod
    def divide(cls, a,b):
        return a / b
    
    @classmethod
    def remainder(cls, a,b):
        return a % b
    
    @classmethod
    def exponent(cls, a,b):
        return a ** b

print(Math.add(360.00,180.9))
print(Math.subtract(300,120.4))
print(Math.multiply(3,3))
print(Math.divide(365,12))
print(Math.remainder(3,2))
print(Math.exponent(2,3))

Inheritance

A class can inherit data or functions from another class. This is called inheritance.

python
class SuperMath(Math):
    def calculateSimpleInterest(self, p,r,t):
        return p * r * t
    def calculateCompoundInterest(self,p,r,t,n):
        compound_interest = p *(1 + (r/n))**(n*t) - p
        return compound_interest

s = SuperMath()

print(s.add(1,2))

print(s.calculateSimpleInterest(10000,.15,5))
print(s.calculateCompoundInterest(1000,.05,10,365))

Importing Classes

If you have two files in the same folder, one called human.py and the other called app.py, you can import code from one to the other using the import statement.

In app.py we import the Human() class inside of human.py. Then we can use all data and methods in the Human class.

python
from human import Human

h = Human()
print(h.name)
python
class Human():
    name = "Joseph"

NOTE

If your classes become too big, it is best to move them into another file and then import them back into your program.

Initializing Objects

You can initialize an object with data. This means you can set some properties on the object as soon as it is created.

python
from human import Human

h = Human("joe",23)
h2 = Human("sarah",32)

print(h.name,h.age)
print(h2.name,h2.age)
h.walk()
python
class Human():
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def walk(self):
        print(f"{self.name} is walking")

Your Turn!

Let's build a Banking System!

  1. Open your code editor
  2. Step 2
  3. Step 3

THINK...

Something to think about

Solution
python
class Bank:
    def __init__(self,name="New Bank"):
        self.name = name
        self.accounts = []
    def add_account(self,x):
        self.accounts.append(x)

class Account:
    def __init__(self,name="New Account",account_holder=None):
        self.amount = 0
        self.name = name
        self.account_holder = account_holder
    def withdraw(self,x):
        self.amount -= x
    def deposit(self,x):
        self.amount += x
    def __repr__(self):
        return str({
            "name": self.name, 
            "amount": self.amount, 
            "account_holder": self.account_holder
            })

chase = Bank("Chase")
print(chase.name)

my_account = Account("Household","Tutorial Doctor")
my_account.deposit(600.00)
my_account.withdraw(100.00)
print(my_account.amount)

chase.add_account(my_account)

print(my_account)

print(chase.accounts)
Discovery

Something you should have gained from this exercise

Resources

W3 Schools