Python, lesson 10
A dictionary like {"name": "Rex", "hunger": 3} works for quick jobs, but as a program grows
you want something sturdier: a type with a fixed set of fields and the operations that belong
to it. That's what a class is. A class is a blueprint; each instance (object) made from
it has its own data.
__init__ runs automatically when you create an instance with Rectangle(3, 4). Its job is
to set up the starting data.self is the instance being worked on. Python passes it for you: box.area() is really
Rectangle.area(box).self.width = width creates an , a variable that lives on the object.2 exercises to try what you just read.
self.Each object keeps its own attributes, so two rectangles never get mixed up.
Create lists and dictionaries inside __init__, not directly in the class body. A list written
in the class body is shared by every instance, which leads to baffling bugs where adding to
one object's list changes them all.
Print an object and you get something like <__main__.Rectangle object at 0x...>. Define
__str__ to control what print() and f-strings show:
Methods with double underscores on both sides are called special methods. Python calls
them for you at the right moment: __init__ on creation, __str__ on printing, __eq__ for
==, and many more.
Many classes are mostly data. Writing __init__, a readable representation and == by hand
for those is repetitive, so the standard library's dataclasses module writes them for you.
You list the fields with type hints:
Fields with defaults must come after fields without them. For a mutable default such as a
list, use field(default_factory=list) so every instance gets a fresh one.
Pass frozen=True to make instances read-only, which is good for values that should never
change, like a coordinate. Pass order=True to make instances sortable by their fields in order.
You can still add your own methods to a dataclass exactly as you would to a normal class.
Finish the Plot class. area() returns width × length, fence() returns the perimeter,
and is_square() returns whether both sides are equal. Each input line holds a width and a
length (whole numbers). The starter prints one line per plot in this form:
Sample input:
Sample output:
Make a @dataclass called Pet with fields name: str, hunger: int = 5 and
mood: int = 5. Add three methods:
feed() lowers hunger by 3play() raises mood by 2 and raises hunger by 1nap() raises mood by 1Neither value may go below 0 or above 10: clamp it after every change. Add __str__ returning
<name>: hunger <hunger>, mood <mood>.
The first input line is the pet's name. Each following line is a command (feed, play or
nap). The starter runs the commands and prints the pet at the end.
Sample input:
Sample output:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
box = Rectangle(3, 4)
print(box.area()) # 12
print(box.width) # 3class Playlist:
def __init__(self, name):
self.name = name
self.songs = [] # each playlist gets its own list def __str__(self):
return f"{self.width}x{self.height} rectangle"from dataclasses import dataclass, field
@dataclass
class Book:
title: str
pages: int
read: bool = False
tags: list[str] = field(default_factory=list)
b = Book("Dune", 412)
print(b) # Book(title='Dune', pages=412, read=False, tags=[])
print(b == Book("Dune", 412)) # True: compares field by fieldarea=12 fence=14 square=False3 4
5 5area=12 fence=14 square=False
area=25 fence=20 square=TrueBiscuit
play
play
feedBiscuit: hunger 4, mood 9