PythonLesson 14 of 16

Classes and objects in Python

A class is a blueprint for objects that carry their own data and actions. A song knows its title and shows its length; a cart holds items and adds up the bill.

Key points

  • class Name: defines a class; the name starts with a capital letter
  • __init__ runs when an object is created and sets its attributes
  • self is the object itself; self.title is where it keeps its data
  • A method is a function inside a class, called with a dot: song.length()
  • Every object is independent: two songs have their own titles

Example

class Song:    def __init__(self, title, seconds):        self.title = title        self.seconds = seconds     def length(self):        return f"{self.seconds // 60}:{self.seconds % 60:02d}" song = Song("Sunrise", 215)print(song.title, song.length())intro = Song("Intro", 65)print(intro.title, intro.length())

Song("Sunrise", 215) creates an object, and __init__ stores the title and seconds in it. The :02d format adds a leading zero, giving 1:05.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

The cart can already add items as (name, price) pairs. Finish the total method so it returns the sum of all prices.

Output

What your program prints appears here.