Summary
In this lesson, you learned that:
- A class says what every object of one kind has and can do:
class Pet:. Class names are written in CapWords. - An object is created by calling its class like a function:
rex = Pet("Rex", "dog", 3). One class can make as many objects as you need, and each has its own values. __init__runs by itself when an object is created. It stores values in the object's attributes, from its parameters (self.name = name) or as a starting value (self.hunger = 5). A missing argument ends with aTypeError.- You read and change an attribute after a dot:
rex.name,rex.age += 1. An attribute that the object doesn't have ends with anAttributeError. - A method is a function in a class,
def describe(self):, and you call it on an object:rex.describe(). Its first parameter,self, is the object it was called on. Python passes it by itself, so a method withoutselfends with aTypeError. Inside a method, an attribute isself.name, notname. - A method can return a value worked out from the attributes, or change them, and keep them sensible, such as a hunger that never drops below 0.
__str__returns the text thatprint()and f-strings show for an object. Without it,print(rex)shows<Pet object at 0x…>.- A list can hold objects. A loop calls a method on each of them, and
max(pets, key=by_age)returns the object with the largest key. - Inheritance:
class Dog(Pet):is a child class that gets everything from its parent class. It can add methods and replace the parent's. When it has an__init__of its own, that calls the parent's withsuper().__init__(…).
In the next lesson, the Final Project, you'll put together what you've learned in this course and build the receipt for an online grocery order step by step, with every item in the cart as an object.
Instructions
- 1
Let's practice with the book from the lesson on dictionaries, this time as an object. In place of the comment, write a class
Book. Its__init__takestitleandpagesand stores them as attributes, and it also creates an attributepage, the page you're on, which starts at0. Add__str__, which returnsThe Hobbit: page 0 of 310. Keep the linehobbit = Book("The Hobbit", 310)as it is. - 2
Add a method
read(self, count)that movespageforward bycountpages, but never past the last page. At the end of the program, callhobbit.read(100)and print the book, thenhobbit.read(250)and print it again. The last two lines should beThe Hobbit: page 100 of 310andThe Hobbit: page 310 of 310.