NOTE: This is a brief tutorial. Check out the documentation on the official python documentation.
What is a class in Python?
In python, a class is a template in which instances can be made out of. Think of it as a template of branches, such as a McDonald's factory. Each time an instance of McDonald's is made, it can do the same things as other McDonald's.
How to Define a Class
In Python, classes are defined using the class
keyword. You type in the keyword and the name. For example, in the McDonald's analogy, I would type
class McDonalds():
#allmcdonalds stuff in here
How to get an Instance
To get an instance, you just have to assign the class to a variable. To do this, you just give the variable var
a value of class()
, where class
is the name of the class. In my example, I would write
washington_dc_mcdonalds = McDonalds()
NOTE: You have to include the parentheses. If I were to do
burger_king = McDonalds
, then burger_king
would become another factory of McDonald's instances.
washington_dc_mcdonalds = burger_king()
would be identical to washington_dc_mcdonalds = McDonalds()
, so be careful.
Class functions
Classes have their own functions. For example, I could put in a function to make Big Macs.
class McDonalds():
bun_slices = 1000
patties = 1000
lettuce = 1000
big_mac_sauce = 1000
cheese = 1000
pickles = 1000
onions = 1000
def big_mac():
bun_slices = bun_slices - 3
patties = patties - 2
lettuce = lettuce - 1
big_mac_sauce = big_mac_sauce - 1
cheese = cheese - 2
pickles = pickles - 4
onions = onions - 1
print('Made a Big Mac with 3 bun slices, two patties, 1 full lettuce, 1 serving big mac sauce, 2 slices of cheese, 4 pickles and 1 full onion.')
return 'big mac'
It would print to terminal how many ingredients it used and return a string with the words 'big mac'
my_mcdonalds = McDonalds()
order = big_mac()
The self variable
In a normal function, if you were to set a variable, such as test = 23
, you could not access the test variable. Typing test
would say it is not defined. This is true in class functions unless they use the self
variable.
A
in the previous function, I would do
class McDonalds():
bun_slices = 1000
patties = 1000
lettuce = 1000
big_mac_sauce = 1000
cheese = 1000
pickles = 1000
onions = 1000
def big_mac(self):
bun_slices = bun_slices - 3
patties = patties - 2
lettuce = lettuce - 1
big_mac_sauce = big_mac_sauce - 1
cheese = cheese - 2
pickles = pickles - 4
onions = onions - 1
print('Made a Big Mac with 3 bun slices, two patties, 1 full lettuce, 1 serving Big Mac sauce, 2 slices of cheese, 4 pickles and 1 full onion.')
return 'big mac'
However, if I were to run the previous code, it would give me an UnboundLocalError
because I tried editing the global variable.
Then if I were to add self to all variables, making the example
class McDonalds():
self.bun_slices = 1000
self.patties = 1000
self.lettuce = 1000
self.big_mac_sauce = 1000
self.cheese = 1000
self.pickles = 1000
self.onions = 1000
def big_mac(self):
self.bun_slices = self.bun_slices - 3
self.patties = self.patties - 2
self.lettuce = self.lettuce - 1
self.big_mac_sauce = self.big_mac_sauce - 1
self.cheese = self.cheese - 2
self.pickles = self.pickles - 4
self.onions = self.onions - 1
print('Made a Big Mac with 3 bun slices, two patties, 1 full lettuce, 1 serving Big Mac sauce, 2 slices of cheese, 4 pickles and 1 full onion.')
return 'big mac'
If I were to run this code however, I would get an error saying that self
is not defined. To define it, we need the __init__
function.
The __init__ function
In a class, when an instance is created, it runs all code in the function every time an instance is created. As a McDonald's, it would not want to form near a Burger King. In our class, we could write
class McDonalds:
def __init__(self):
bk = burger_king_nearby() #this is not real, it is just an example function.
if bk:
raise Exception('There is a Burger King nearby, you cannot put a McDonalds here.')
The code would check for a burger king, and if it finds one it will give the user an error saying that there is a Burger King nearby. The __init__ function can also assign self variables. In our previous example, it would say self does not exist. Now, we could write
class McDonalds():
def __init__(self):
bk = burger_king_nearby() #this is not real, it is just an example function.
if bk:
raise Exception('There is a Burger King nearby, you cannot put a McDonalds here.')
self.bun_slices = 1000
self.patties = 1000
self.lettuce = 1000
self.big_mac_sauce = 1000
self.cheese = 1000
self.pickles = 1000
self.onions = 1000
def big_mac(self):
self.bun_slices = self.bun_slices - 3
self.patties = self.patties - 2
self.lettuce = self.lettuce - 1
self.big_mac_sauce = self.big_mac_sauce - 1
self.cheese = self.cheese - 2
self.pickles = self.pickles - 4
self.onions = self.onions - 1
print('Made a Big Mac with 3 bun slices, two patties, 1 full lettuce, 1 serving Big Mac sauce, 2 slices of cheese, 4 pickles and 1 full onion.')
return 'big mac'
This code will check for a Burger King. If it does not find one it will give the store all of its ingredients.
Finalizing the class
However, there is one more problem with this class. The ingredients will go below zero if used repeatedly. We cannot let that happen. In classes, we can run functions in the class multiple times if run as self.function()
where function is the name of the function.
To fix the problem, we can just have a function that asks for ingredients if the ingredients will go below zero and run it every time a recipe is created.
def call_HQ_for_ingredients(anything):
time.sleep(100) # 1 business day, jk
return 1000
class McDonalds():
def __init__(self):
bk = burger_king_nearby() #this is not real, it is just an example function.
if bk:
raise Exception('There is a Burger King nearby, you cannot put a McDonalds here.')
self.bun_slices = 1000
self.patties = 1000
self.lettuce = 1000
self.big_mac_sauce = 1000
self.cheese = 1000
self.pickles = 1000
self.onions = 1000
def check_for_ingredients(self):
if self.bun_slices < 10:
self.bun_slices = self.bun_slices + call_HQ_for_ingredients('bun slices') # once again not real
#repeat with other ingredients
def big_mac(self):
self.check_for_ingredients()
self.bun_slices = self.bun_slices - 3
self.patties = self.patties - 2
self.lettuce = self.lettuce - 1
self.big_mac_sauce = self.big_mac_sauce - 1
self.cheese = self.cheese - 2
self.pickles = self.pickles - 4
self.onions = self.onions - 1
print('Made a Big Mac with 3 bun slices, two patties, 1 full lettuce, 1 serving Big Mac sauce, 2 slices of cheese, 4 pickles and 1 full onion.')
return 'big mac'
Accessing class variables
Let's say that there was a mistake and that the stores started with 2000 pickles. To change this, the variable could be accessed from the class instance.
McDonalds1 = McDonalds()
print(McDonalds1.pickles)
McDonalds1.pickles=2000
print(McDonalds1.pickles)
Now it will say 1000 pickles at the beginning, but after changing the variable there are 2000 pickles.
Why use a class instead of a function?
Classes are special due to the fact once an instance is made, the instance is independent of all other instances. I could make two instances of the McDonald's that run independently of each other.
USA_mcdonalds = McDonalds()
UK_mcdonalds = McDonalds()
USA_customers = 2
UK_customers = 1
#for customer in range(len(USA_customers)):
# Will throw TypeError: object of type 'int' has no len()
for customer in range(USA_customers):
order = USA_mcdonalds.big_mac()
#for customer in range(len(UK_customers)):
# Will throw TypeError: object of type 'int' has no len()
for customer in range(UK_customers):
order = UK_mcdonalds.big_mac()
print(USA_mcdonalds.patties)
print(UK_mcdonalds.patties)
They will have different patty counts.
Exceptions
Exceptions are a class that just will raise when used with the raise keyword. The Exceptions subpage has more info on it.