Skip to contentSkip to navigation

Module 4 of 6, Practical Python

Classes and Objects

Model things as classes with their own data and behaviour, and build on them with inheritance.

module checksSign in to track

  • Lessons complete-, not done
  • Lesson quizzes taken-, not done
  • Module Labs passed-, not done
  • Module exam passed at 80%-, not done
lessons
3
quiz questions
36
reading time
24 min
exam length
15 Q
coding exercises
6

Lessons

  1. Classes and ObjectsBuild your own types: define a class, create objects from it, give them attributes and methods, and see why bundling data with behaviour keeps programs tidy. 8 min 12 questions
  2. Constructors, self and AttributesSet objects up properly: give __init__ defaults and validation, tell instance attributes from class attributes, avoid the shared-list trap, and make objects print nicely with __str__ and __repr__. 8 min 12 questions
  3. Inheritance and Method OverridingBuild classes on top of other classes: inherit attributes and methods, override what differs, extend a parent's method with super(), and treat related objects the same way. 8 min 12 questions

Lab: write it yourself

Real Python, real checks: write your answer, press Run checks, and keep going until it passes. (3 exercises)

All module exercises

The Lab needs an account. Sign in or create a free ID to run these exercises.

Lab 1: Rectangle class

Sign-in required

Create a class Rectangle with __init__(self, width, height) and a method area(self) returning width * height. Test with r = Rectangle(4, 5) and print: Area: 20.

Sign in to practise

Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and save your practice. Practice does not award XP.

Lab 2: A Dog class

Sign-in required

Create a class Dog whose __init__ takes name, with a method bark() returning "{name} says Woof". Print Dog("Rex").bark().

Sign in to practise

Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and save your practice. Practice does not award XP.

Lab 3: Inherit and override

Sign-in required

Animal.speak() returns "...". Make Cat(Animal) override it to return "Meow", then print Cat().speak().

Sign in to practise

Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and save your practice. Practice does not award XP.

References & Further Reading

Related entries from PyLabs's own reference library.

  • property() (Create a managed attribute for a class.)
  • classmethod() (Make a method receive the class instead of an instance.)