Applied PythonLesson 17 of 1917 min
Classes and Objects
Bundle data with the functions that operate on it, and model things in your problem domain.
By the end you will be able to
- Define a class with __init__ and instance attributes
- Write methods that use self
- Give a class a readable __str__
You have already used objects constantly — every string, list, and dict is one, and methods like .append() are functions attached to them.
A class lets you define your own kind of object: a template that bundles data (attributes) with behaviour (methods).
Rex 3
Rex says woof!
Bella says woof!
Bella is 35 in human years
— expected output; press Run to execute it yourselfMethods that change state
Attributes can be updated like any variable. Methods that mutate the object are how you keep the rules in one place, rather than scattering them across the program.
120
[('deposit', 50), ('withdraw', 30)]
Rejected: insufficient funds
— expected output; press Run to execute it yourself__str__: printing something useful
By default, printing an object shows an unhelpful <__main__.Dog object at 0x...>. Define __str__ to control that.
Point(0, 0)
Point(3, 4)
5.0
— expected output; press Run to execute it yourselfInheritance
A class can build on another, keeping what fits and replacing what does not. super().__init__(...) runs the parent's setup so you do not repeat it.
Tom says meow
Daisy says moo
Rex says yip
— expected output; press Run to execute it yourselfExercise
Write a Rectangle class taking width and height. Give it an area() method, a perimeter() method, and a __str__ returning Rectangle 3x4.
Press Run to execute this code.