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 Style | The program is built from | Where the data lives | We use it for |
|---|---|---|---|
| Procedural | Functions that run step by step | Plain variables, lists, and dictionaries that functions change | Loops, lists, dictionaries, files |
| Functional | Functions that take values and return new ones | Passed in and returned, not changed | lambda, map, filter, higher-order functions, recursion |
| Object-Oriented | Objects that bundle data with methods | Inside each object | Classes 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.
- Its methods are functions that belong to the object. They describe what the object can do, so they are also called its behaviors.
- Its attributes are pieces of data that describe the object and represent what it is like right now. Together, they make up its state. For example, the string "hello" has the characters h, e, l, l, and o. These characters represent the data stored in the string object.
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 example | Programming concept | |
|---|---|---|
| What it has | Size, price, toppings | Attributes |
| What it does | Add toppings, slice | Methods |
| What it is right now | Large, $15, pepperoni | State |
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 theclass 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:
3Constructor
If we want to add attributes (like price, toppings, size) we need to add a special method to out class, calledconstructor . 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.
- Python creates a new, empty
Pizzaobject. - Python calls
__init__. The new object is passed in asself, followed by the arguments you wrote in the parentheses. __init__stores the starting values onself.- The finished object is handed back, and the name
pis 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.
__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:
size: the size that was passed in.toppings: the list that was passed in.price: the base price fromPRICESfor that size, plus 1 for each topping.
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.
Pizza one more time:
self.size refers to the size attribute of the particular pizza being created.pizza1 and pizza2 are two different objects.size attribute.