DSC 20 Reader · Classes and Objects
Starting Python…

Course weeks 7–8

Object-Oriented Programming

Up to now, we have used two programming styles: procedural and functional. In both, data and the functions that work on it live in separate places. An object-oriented approach puts them together: a class describes a kind of thing once, and each object made from it carries its own data and its own methods, the functions that work on that data.

Side by side

Programming StyleThe program is built fromWhere the data livesWe use it for
ProceduralFunctions that run step by stepPlain variables, lists, and dictionaries that functions changeLoops, lists, dictionaries, files
FunctionalFunctions that take values and return new onesPassed in and returned, not changedlambda, map, filter, higher-order functions, recursion
Object-OrientedObjects that bundle data with methodsInside each objectClasses and objects

1Objects.

You have been working with objects since the first week. A string is an object of type str, and .upper() is a method. A list is an object of type list, and .sort() changes that particular list.

An object bundles two things:

Let's create a custom object, pizza. But first we need to decide what kind of methods and attributes this object may have.

Pizza object

Pizza exampleProgramming concept
What it hasSize, price, toppingsAttributes
What it doesAdd toppings, sliceMethods
What it is right nowLarge, $15, pepperoniState

A class lets you define new types like these. We will build one class, Pizza, that keeps track of how many pizzas were ordered.

2Defining a class

A class describes what an object looks like. Each object made from it is called an instance. The class is the recipe, and every instance is one thing made from that recipe.

To define a class in Python, you use the class keyword followed by the class name and a colon. The following example defines a Pizza class:
class Pizza:
    pass

By convention, Python class names start with a capital letter. If a class name consists of multiple words, capitalize the first letter of each word and write them together, without spaces. This naming style is called CamelCase. For example, PizzaSlice.

Since the Pizza class does not contain any code yet, you can use the pass statement as a placeholder. It tells Python that the class is intentionally empty for now and that you can add its implementation later.

To create an instance of a class, you use the class name with parentheses like this:

pizza = Pizza()
Now let's put all pieces together and print the pizza object:
The output is not very informative: Python displays the name of the class and the memory address of the object. It is time to make our class more interesting so that it can create tasty pizza objects!

3Constructor

If we want to add attributes (like price, toppings, size) we need to add a special method to out class, called constructor . A constructor is a special method that Python calls automatically when you create a new object. It initializes the object's attributes with their initial values.

Writing a constructor

In Python, the constructor is a special method named __init__, with two underscores on each side. Its first parameter is always self, which refers to the new object being created. Python passes this object to the method automatically. The remaining parameters represent the values you provide when creating the object. Inside the method, a statement such as self.size = size stores a value in the object's size attribute.

You never call __init__ by name. Writing Pizza("large", 15, ["pepperoni"]) makes Python do four things in order.

  1. Python creates a new, empty Pizza object.
  2. Python calls __init__. The new object is passed in as self, followed by the arguments you wrote in the parentheses.
  3. __init__ stores the starting values on self.
  4. The finished object is handed back, and the name p is attached to it.

Now that the constructor asks for three values, the plain call you started with, Pizza(), no longer works. Run the cell and read the message.

Python says three required arguments are missing, and names them. It means you need to pass the data in order to create an object.

Every object gets its own values

Each call to the class runs the constructor again, and each pizza gets its own attributes.

Quick check
When does Python run __init__?

A constructor can calculate

A constructor does not have to copy its parameters. It can work out an attribute from the others. Here the price comes from the size, so the caller does not need to know it.

Show the fix

The message says __init__() takes 1 positional argument but 2 were given. Python passed the new object and "large", but the method only listed one parameter. Write def __init__(self, size):, then store the value with self.size = size.

Exercise: build the Pizza constructor

Write the constructor for Pizza(size, toppings). It should set three attributes:

Hint

Store size and toppings on self the same way as in the earlier examples. For the price, look up the base price with PRICES[size]. The function len(toppings) gives the number of toppings, which is also the extra cost.

Show a solution
PRICES = {"small": 9, "medium": 12, "large": 15}

class Pizza:
    def __init__(self, size, toppings):
        self.size = size
        self.toppings = toppings
        self.price = PRICES[size] + len(toppings)

4self

What is self?

You might be wondering what self means. Think of it as a way for an object to refer to itself. When you create an object, Python needs a way to know which object you are working with. That's what self is for.

For example, consider this statement: self.size = size It means: "Store the value of size in the size attribute of this particular object."

The name self is a convention in Python. You could technically use another name, but you should always use self to make your code easier to read and understand.

The good news is that you don't need to pass self yourself when creating an object. Python supplies it automatically.

Let's refer to out class Pizza one more time:
  • self.size refers to the size attribute of the particular pizza being created.
  • pizza1 and pizza2 are two different objects.
  • Each object has its own size attribute.