Classes & Objects

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

Classes and Objects

Like many programming languages, Python supports object-oriented programming where classes are templates that define the data and behavior of objects, which are instances of those classes. If you’ve worked with other languages that support OOP, you’ll find Python’s support for it familiar, but you might be surprised by the syntax.

Defining a Class

Class definitions begin with the class keyword followed by the name of the class. By convention, classes are named using the CapWords or PascalCase convention, where the first letter of every word in the name is capitalized. All indented code under class ChecklistItem: is part of the class.

The Docstring

Like functions, classes can have docstrings, strings that act as documentation, that immediately follow their first line. Also, like functions, you can access the docstring via the class’ __doc__ property. Try it by running this in a code cell: print(ChecklistItem.__doc__).

Class Attributes

Any variable, or in this case, variable being used as a constant, defined inside the class body but outside any method is a class attribute. The value of a class attribute is shared among all class instances.

The __init__() Method

The first method in the class is __init__(), the built-in initializer method for classes. Its name is often pronounced dunder init, and the double underscores surrounding its name indicates that it’s a special method.

Creating a New Instance

Creating a new instance of a class in Python is straightforward:

Instance Attributes

Two of the three instance attributes of ChecklistItem instances are defined in the __init__() method by these lines:

Defining and Calling Methods

The two methods after the __init__() method are:

The __str__() and __repr__() Methods

There are two more methods after priority_emoji() and set_priority(), both of which are “dunder” methods (methods whose names begin and end with double-underscores) that are built into Python classes:

Properties

Properties are a special attribute that lets you define behind-the-scenes getter and setter methods that look like directly accessing the attribute. They’re similar to C#’s, Kotlin’s and Swift’s properties, or JavaScript’s get and set methods.

Inheritance

Like most programming languages that support object-oriented programming, Python supports class inheritance.

See forum comments
Download course materials from Github
Previous: Functions: Deep Dive Next: Writing Python Code Demo