Python Intermediate Concepts Tutorial

Intro to Designing Classes

Python is an object-oriented programming language that is ideal for creating reusable patterns of code.

An important concept in Python is to distinguish classes and objects:

A class is a blueprint created by a programmer for an object. This defines the logic for attributes and methods that can characterize an object instantiated from this class.

A object is an instance of a class. This is the implemented version of the class and the underlying attributes - both variables and methods - can be utilized in the python program.

Together, classes create patterns and objects make use of the patterns.

This tutorial will cover how to create classes, create an instance object of a class and create attributes of a class through variables and instance methods.

Classes

I can define a class using the class keyword. Below is the simplest example possible. However, the class below is empty and not a good use case of creating a reusable pattern.

Class names should use the CapWords convention - as in each word should be capitalized and chained to one another without an underscore. This is best practice laid out in the Python style guide.

This class will be like a pizza shop. I eventually expect it to take in orders, make pizza and deliver orders.

In [62]:
class PizzaShopOrder(object):
    pass

The Constructor Method

The __init__ method below is a special method that gets called when the object is instantiated - also known as creating an instance of the class. The __init__ method is commonly referred to the constructor method.

The constructor method usually stores attributes of the instance of the class.

I can create an empty constructor method as seen below.

Notice how the first argument to the constructor method is self. This is needed! It's a reference to objects made on this class.

In [63]:
class PizzaShopOrder(object):
    def __init__(self):
        pass
        # this is the constructor method

I want to initialize an instance of the PizzaShopOrder class. I can do so with the following syntax.

Another way of saying this is I assign the variable pizza_object to be an instance of the PizzaShopOrder class.

In [64]:
pizza_object = PizzaShopOrder()

The constructor method usually holds attributes related to a class instance. I want to assign attributes necessary for the pizza shop in dealing with an order. Every order must be a request for a pizza type, size and quantity.

For example, I often order a style of pepperoni, size of a slice and a quantity of 1.

The parameters of the constructor method typically have the same names as the attributes.

Below, self.size stores the parameter of the size as an attribute of self.

In [65]:
class PizzaShopOrder(object):
    def __init__(self, style, size, quantity):
        self.style = style
        self.size = size
        self.quantity = quantity

Given these new attributes, I want to create a new instance of the class. I must provide arguments to the instance of PizzaShopOrder.

In [66]:
pizza_object = PizzaShopOrder(style="pepperoni", size="slice", quantity=1)

I can reference these attributes of the pizza_object using the dot operator. I want to reference the variables initialized in the constructor method.

In [67]:
pizza_object.style
Out[67]:
'pepperoni'

Additionally, I can set default values for the class attributes. For example, the class PizzaShopOrder2 (note the name difference because of the 2 at the end) below has default arguments for size and quantity. This may be realistic for a pizza shop because most people likely order 1 slice by default.

In [68]:
class PizzaShopOrder2(object):
    def __init__(self, style, size="slice", quantity=1):
        self.style = style
        self.size = size
        self.quantity = quantity

I can create an instance of the PizzaShopOrder2 class and access the values of these attributes.

Let's assume someone orders just a "cheese".

In [69]:
pizza2_object = PizzaShopOrder2(style="cheese")

The default values for quantity and size should still hold.

In [70]:
pizza2_object.quantity
Out[70]:
1
In [71]:
pizza2_object.size
Out[71]:
'slice'

As expected, by default the pizza shop sassume the order is for a quantity of 1 for a slice.

Instance Methods

The pizza shop receives an order based on a size, style and quantity request. Next, it should make the pizza and serve it.

Below I define two instance methods in the class. For now, these instance methods simply print out a statement. These instance methods are only available to an object that's an instance of PizzaShopOrder().

In [72]:
class PizzaShopOrder(object):
    def __init__(self, style, size, quantity):
        self.style = style
        self.size = size
        self.quantity = quantity
        
    def make(self):
        print("The pizza is being made...")
        
    def serve_pizza(self):
        print("The pizza has been served!")

Let's create a new object as an instance of the class. Let's assume the order is for 1 mushroom slice. Let's make the pizza and serve it!

In [73]:
mushroom_slice_order = PizzaShopOrder(style="mushroom", size="slice", quantity=1)

I can reference an attribute of the mushroom_slice_order object using the dot operator. I'll call the two instance methods created above.

In [74]:
mushroom_slice_order.make()
The pizza is being made...
In [75]:
mushroom_slice_order.serve_pizza()
The pizza has been served!

However, I recall when I visited pizza shops, after the pizza is made, the chef would state the order out loud that's ready to be served. Then I'd walk to the front counter and pick it up. I'll modify the serve_pizza() instance method to account for this!

The instance methods can utilize the attributes defined in the constructor method.

In [76]:
class PizzaShopOrder(object):
    def __init__(self, style, size, quantity):
        self.style = style
        self.size = size
        self.quantity = quantity
        
    def make(self):
        print("The pizza is being made...")
        
    def serve_pizza(self):
        print(f"{self.quantity} {self.size} {self.style} is ready!")
In [77]:
cheese_slice_order = PizzaShopOrder(style="cheese", size="slice", quantity=1)
In [78]:
cheese_slice_order.make()
The pizza is being made...
In [79]:
cheese_slice_order.serve_pizza()
1 slice cheese is ready!

This tutorial covered how to create a class, create an instance of a class and initialize attributes with the constructor method. There are many more important concepts with object-oriented programming in Python such as inheritance that will be covered in other tutorials.

You can learn more about class in Python on the official documentation page.