image
Introduction to Classes in Python

Contents

Introduction to Classes

The course is part of this learning path

Introduction to Classes in Python
Difficulty
Beginner
Duration
11m
Students
99
Ratings
5/5
starstarstarstarstar
Description

This course introduces Classes in Python and is part of a series of content designed to help you learn to program with the Python programming language. 

Learning Objectives

  • Classes are conceptually templates for creating new types of objects
  • Classes can include two types of attributes
  • Classes can include two types of methods
  • Classes can define a constructor by using the init method

Intended Audience

This course was designed for first-time developers wanting to learn Python. 

Prerequisites

This is an introductory course and doesn’t require any prior programming knowledge.

 

Transcript

Hello, and welcome! My name is Ben Lambert, and I’ll be your instructor for this course. This course is part of a series of content designed to help you learn to program with the Python programming language. 

Should you wish to ask me a specific question, you can do that with the contact details on screen. You can also reach support by using the email address: support@cloudacademy.com. And one of our cloud experts will reply.

In this lesson, we’re going to explore how to create new types of objects. The Python runtime is built around the idea of objects. Objects are used to model real world and abstract concepts. 

The way that we model a concept is to break it down into data and behaviors. In terms of objects we call these attributes and methods. Attributes define some meaningful aspect of the concept. And methods define some meaningful behavior of the concept.

The Python runtime includes many built-in object types. Strings, integers, floats, lists, sets, dictionaries, booleans, callables, and the list goes on for a while. Even with all of the built-in types it’s common to need to create our own objects. 

Python’s language syntax includes rules for creating new object types. These rules allow us to define new object types by specifying the attributes and methods that will exist when the object is created. The syntax for creating new types is to use the class keyword. 

Before we review the syntax for creating a class let’s break down the anatomy of a class. Classes are conceptually templates for creating new types of objects. They enable us to define attributes and methods. 

When the interpreter reads a class definition it creates a new object type. We use that new type to create objects with those attributes and methods. Because classes are conceptually templates we can use them to create multiple instances of any given type. 

For example, we can create multiple numbers, strings, lists, etc. So each class definition creates a new object type. And each object is an individual instance of its type. Classes allow for two types of attributes. These are called class attributes and instance attributes. The difference between them is based on how we interact with them in code. 

Class attributes are used to define attributes which apply to the type itself. Instance attributes are used to define attributes which are isolated to each instance of an object. Let’s illustrate this to better explain. Imagine we have a class named Greeter. Its purpose is to greet someone when the greet method is called. This class has two attributes. The first is a class attribute which is used to store the default greeting. 

The second attribute is the name of the individual to greet. This is an instance attribute. The greet method prints a message to the console which includes the default greeting and the individual’s name. 

Let’s create two instances of this Greeter type. The first will have a name of: human and the second will have the name robot. Calling the greet method for each will take the default greeting which is currently set to hey, and combine it with the name. 

These instance attributes are each specific to their own objects. If we change one of these it doesn’t impact the others. Class attributes on the other hand are applied to the type itself. Imagine that we change the greeting from hey to something else. 

Now if we call the greet function for each object instance, we can see that they both reflect the new greeting. Class attributes are useful in specific circumstances. For example, setting a default value of some sort.

This is an important concept to understand because misusing class attributes could result in unexpected behaviors in your code. For example, imagine if both of these objects attempted to modify the class attribute as if it was an instance attribute. 

They would both me modifying the template itself rather than their own instance attributes. And they’d be overwriting each other’s changes. So, class definitions can have two types of attributes: class and instance attributes. 

Methods also have two types. Which are class and instance methods. Class methods are basically functions which are attached to the class template. Instance methods are methods which have access to the instance attributes of the object. 

Class methods are useful for certain tasks. However, instance methods are perhaps more common due to their ability to access instance attributes. Let’s review the syntax for creating a new object type using the class keyword.

We start a new class with the class keyword followed by the name of the new type and then a colon and new line. The code block which defines the class is indented using the standard indentation. Attributes set in the class body are considered class attributes. The syntax for creating one follows the name binding syntax. Which specifies the attribute name - the assignment operator and the object to bind. 

Methods are defined using the same syntax used for creating functions. Recall that methods are a type of callable object similar to functions. Callables are named pieces of code that will run when called.  Callables accept (optional) input. Then they perform some action. Then they return the results. 

Since methods are callables, they follow this same pattern. They can accept input and return output. Methods are almost identical to functions except for one aspect. Methods are either attached to a class or instance. Being attached is how the methods are able to access either class or instance attributes. 

The mechanism that the runtime uses to provide us access to attributes from inside a method is through a required input parameter. The first input parameter for an instance method is bound to the current object instance. 

This is different from functions. Because with functions we can specify all the input parameters. However, with methods, the Python runtime reserves the first input spot. Whatever name is in the first spot will be automatically bound by the runtime to the current object.

While this argument name can be any valid name, the standard is to name it self. I highly recommend that you follow this standard. So, when a method is called, the Python runtime will automatically provide the current object as input. The self name becomes a stand-in for the current object, enabling us to interact with the other attributes and methods of the object.

This is a common source of confusion for individuals who are new to programming. So let’s see an example. Here I have a Counter class with a method for count. The count method includes two input parameters. The first is named self. 

Self represents an instance of the object. It enables us to access the number instance attribute, which is where we’re storing the count. The second input parameter is named plus. It specifies how much we add to the number when count is called. 

If we create an instance of a Counter and bind it to the name counter we can interact with it a bit. Notice the count method includes two input parameters. However, when we call it, we only provide one. That’s because Python automatically provides the first. 

This is the big difference between a function and a method. The method is linked to either a class or instance. When linked to an instance the first parameter is commonly named self. When the method is a class method, the first parameter is commonly named cls. And it will have access to class attributes.

Let’s explore how to define instance attributes. Class attributes are defined anywhere in the body of the class definition. Instance attributes are defined inside methods by using the self name binding. Instance attributes can be created inside any method, however, it’s common that you’ll want to create them when the object is first created. The Python runtime defines a series of methods which control an object’s behavior. 

One of those methods is the init method which is called when the object is first initialized. Any code inside the init method will be called when the object is created. This provides us with a mechanism for controlling how objects are  constructed. Which is why this init function is referred to as a constructor. 

In this example with the Counter the constructor accepts one input parameter named self. Using self as a stand-in for an instance we can bind the attribute number to the current instance and set its value to zero.

Because this is set to zero Python knows that this is an integer. Which makes it possible for us to perform some addition using this binding inside the count method. This increment operator increases the number by the amount specified in the plus name binding. 

The constructor is quite flexible allowing us to specify input arguments as needed. For example, we could require that the initial number is provided when the object is created. Let’s see what that would look like. 

By adding a new input parameter for default_number we can require that this number is provided when the class is created. 

The interpreter converts a class definition into a new object type. That object type is callable. That’s why we use the same syntax for creating an object that we use for calling a function or method. We provide any input required by the constructor and we’re given a new object in return.

A common question for beginners when seeing the constructor is: what’s with its name? The two underscores on each side of the word init indicate that this is a special method used for controlling the object’s behavior. 

Python provides a series of built-in methods that we can use to control objects in different ways. This method is used to run code when the object is created. There are many others. For example: there are methods which control how an object interacts with operators. 

Understanding these methods allows us to make our own objects that behave more closely to the built-in objects. However, these are a rabbit hole for another lesson. Okay, this seems like a natural stopping point. Here are your key takeaways for this lesson:

  • Classes are conceptually template for creating new types of objects

  • Classes can include two types of attribute:

    • Class attributes which are linked to the type

    • Instance attributes which are linked to an object instance 

  • Classes can include two types of methods:

    • Class methods are linked to the type and have access to class attributes and other class methods.

    • Instance methods are linked to an object instance and have access to both class and instance attributes and methods.

  • Classes can define a constructor by using the init method

That's all for this lesson. Thanks so much for watching. And I’ll see you in another lesson!

About the Author
Students
99634
Labs
33
Courses
45
Learning Paths
54

Ben Lambert is a software engineer and was previously the lead author for DevOps and Microsoft Azure training content at Cloud Academy. His courses and learning paths covered Cloud Ecosystem technologies such as DC/OS, configuration management tools, and containers. As a software engineer, Ben’s experience includes building highly available web and mobile apps. When he’s not building software, he’s hiking, camping, or creating video games.

Covered Topics