Skip to content
CodeNest

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).

Python
Output
Rex 3
Rex says woof!
Bella says woof!
Bella is 35 in human years
— expected output; press Run to execute it yourself

Methods 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.

Python
Output
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.

Python
Output
Point(0, 0)
Point(3, 4)
5.0
— expected output; press Run to execute it yourself

Inheritance

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.

Python
Output
Tom says meow
Daisy says moo
Rex says yip
— expected output; press Run to execute it yourself

Exercise

Write a Rectangle class taking width and height. Give it an area() method, a perimeter() method, and a __str__ returning Rectangle 3x4.

Python
Output

Press Run to execute this code.

Check your understanding

0/3 answered
  1. 1.When does __init__ run?
  2. 2.What does self refer to inside a method?
  3. 3.What does super().__init__(name) do in a subclass?