1.3 Classes and Objects in Python

Introduction

Now that we have started to get used to the idea of thinking about designing and modeling classes of objects, let's now learn how to code these classes in Python.


Class Definitions

The syntax for defining a class is quite simple.

class MyClassName:

    attribute_1 = 0
    attribute_2 = ""

    def __init__(self, param1, param2):
        # Code for the constructor goes in here

    def some_function(self, param1, param2):
        # Function codes goes here

The first thing you will notice is the keyword class followed by the name of the class, and then a colon indicating the start of a code block. Next, we have the attributes for the class listed with some initial values. After the list of attributes we have the function definitions for the class. The first function might seem a bit strange. Notice its name, __init__; this is a special function called a constructor. A constructor is run when a new instance of a class is being created. We can use a constructor to set certain attributes at the time it is being created, for example. Or, we can just leave it out all together, as the constructor definition is optional.

Ok, let us now create an actual class of our own. Before we start to write code, let us first plan out a class which we shall code.

PAGE
--------------------
page_number
title
content
--------------------
set_page_number
set_title
add_content
get_page_number
get_title
get_content

Now that we have planned out our class structure, let's start coding. To get going, let us create a new file called page.py, and this is the code we shall place in the file.

class Page:

    page_number = 0
    title = ""
    content = ""

    def __init__(self, page_no):
        self.page_number = page_no

    def set_page_number(self, page_no):
        self.page_number = page_no

    def set_title(self, new_title):
        self.title = new_title

    def add_content(self, new_content):
        self.content = self.content + new_content

    def get_page_number(self):
        return self.page_number

    def get_title(self):
        return self.title

    def get_content(self):
        return self.content

Note: You will notice when using class attributes within the class functions, we prefix the attributes with self. which specifies that we are using the attributes of the object instance.

The class definition above should be quite straight forward, as we have just implemented the attributes and functions as defined in our previous outline of the class. Let us move on to creating instances of this class.


Creating Object Instances

To create an instance of an object, we use the following simple syntax:

some_variable = MyClass()

This will then run the init() function of the class, prepare the data structures contained within the class, and place the new object in memory, with the variable pointing to that address.

With our Page class example above, if we wanted to create three pages, we could do so in the following way:

first = Page(1)
second = Page(2)
third = Page(3)

Notice that we are passing an integer when creating the objects. If we take a look at the init() function for the Page class, we see it is structured as follows:

    def __init__(self, page_no):
        this.page_number = page_no

Here, it takes in a page_no variable as a parameter to the function, and assigns the value of this variable to the class' page_number attribute. Once we have the objects, we can start using them. To access their attributes or functions, we use the object's identifier, followed by a point (.) followed by the attribute or function. Let's look at an example:

first.title = "The First Page"
first.add_content("Welcome to the first page. Here is a bunch of content")
first.get_page_number()
[Output: 1]

Static Methods

Static methods are functions of a class which can be called without needing an object instance of the class. To make a function within a class a static function, we prefix the function with the @staticmethod decorator. Here is the syntax:

class SomeClassName:
    @staticmethod
    def my_static_function(param1, param2):
        # Implementation code goes here

SomeClassName.my_static_function(val_1, val_2)

Note that the first parameter in the my_static_function() static method is not self, as is the case with non-static methods. This is because static methods are called without an object instance of the class, meaning there will be no such thing as "self" when the function is run.


Exercises

  1. Write a class for contact entries in a phone book, and populate an array with 10 contacts. Then loop through the contacts and print out each entry in the following format: "#1 Firstname Lastname : PhoneNumber"
  2. Write a class for Website data. Then populate an array with your favorite websites. Once done, loop through the array and print out data for each object as follows: "#1 WebsiteName: URL"

Further Reading for the section

  1. Python: Classes
  2. Think in Python

Continue to the next section


Comments

comments powered by Disqus