Skip to main content
Enchanted Code

Python 3 objects

tutorial, python

Intro

This tutorial will teach you about object orientated programming in Python 3.

Requirements

  • Know basics of Python 3 if not read here
  • Know common data-types in Python 3 if not read here
  • Knowledge of OOP in computer science will help

What are they?

Python is a object orientated language, this means that nearly everything in Python is considered an object. Objects allow us to create code that can be re-used and inherited by other objects decreasing the amount of repeated code.

Python’s classes are considered the blueprint for objects to be created. An object will have it’s own attributes and methods that allows them to have functionality.

Defining

Before we create a object we have to create the blueprint. This can be done using the class keyword in Python.

Parent

When creating a class we first have to decide whether we are going to inherit from another or create a new base class that will act as the parent.

In this section we will be creating a class that will contain features of an animal. As you can see from the code below we are creating some variables that are called properties in a class. We will be giving them a default value of None, this is because we will be setting the values in our inherited classes (the children).

class Animal:
    colour = None
    type_ = None
    breed = None
    sound = None

Children

Now we can move on to creating children from our parent class Animal. In this code we will be creating two children: Dog and Cat.

As you can see from the code they are inheriting from the parent Animal. This is done through the brackets at the end of the class’s name. We are also overriding the attributes defined in the parent class.

At the moment we can’t really do much with our classes so we will need to add some methods to add functionality.

class Dog(Animal):
    type_ = "dog"
    sound = "woof"


class Cat(Animal):
    type_ = "cat"
    sound = "meow"

Adding Functionality

Now lets add some functionality. As you can see from the code we are using something you might not have seen before, that being: __init__. This is the constructor for the class, it will be called when we create an instance. The animal class also has a new method called make_sound.

As you can see there is a new keyword self, this is references the instance of the class it is required for all methods (unless they are defined as static methods). Using self we can access the object’s attributes and methods.

class Animal:
    colour = None
    type_ = None
    breed = None
    sound = None

    def make_sound(self):
        print(self.sound)


class Dog(Animal):
    type_ = "dog"
    sound = "woof"

    def __init__(self, colour, breed):
        self.colour = colour
        self.breed = breed

Go ahead and extend the functionality of the cat class, using what you have learned here.

Instantiating

Now we have created a class with some functionality lets use it. To use a class we have to instantiate it. We can achieve this in a similar way that we call a function and store its returned value.

As you can see from the code we are instantiating two objects into the variables dog_one and dog_two. We are setting the colour and breed using the constructor.

dog_one = Dog("black", "spaniel")
dog_two = Dog("golden", "labrador")

Accessing

Now we have our two objects we can use them. In Python we can access properties and methods. In this code example it will output the dogs breed and compare whether the sound of one dog is similar to the other one. We are also running the make_sound method.

print(dog_one.breed)
print(dog_two.breed)
print(dog_one.sound == dog_two.sound)

dog_one.make_sound()

This code should output the following:

spaniel
labrador
True
woof

We can also modify the properties once we have instantiated them. As you can see from the code we have created a new animal using just the parent.

owl = Animal()

owl.colour = "brown & white"
owl.type_ = "owl"
owl.breed = "barn"
owl.sound = "hoot"

print(owl.sound == dog_one.sound)
owl.make_sound()

When running our code we should see that it outputs that the sound is not the same as a dog and we should get the output of our owl.

False
hoot

Extras

Python classes also have extra functionality. I will show some examples of some of them here.

Static Method

This allows us to create static methods which do not require the class to be instantiated to use.

As you can see you place @staticmethod above a method that you want to make static. In Python the @ operator is used for using decorators.

Further detail of decorators are not covered in this tutorial

class MathHelper:
    PI = 3.14159

    @staticmethod
    def area_of_circle(radius):
        return MathHelper.PI * radius**2

    @staticmethod
    def area_of_square(width):
        return width * width

print(MathHelper.PI)
area_of_circle = MathHelper.area_of_circle(5)
print(area_of_circle)

When this code runs it should output the value of PI and the area of a circle with the radius of 5.

3.14159
78.53975

Class Method

Class methods allows us to use something similar to what would be known as method overloading in other languages e.g. C++ or C#.

Like a static method you need place a decorator above the method you want to convert. In this case you will need to place @classmethod above. However unlike the static method you will need a cls parameter this will be a reference of which class the method was called from.

As you can see from the code we don’t have to include a type argument for each pet if they are a dog or cat, we just pass in the pets name and age.

We could do some conversion or extra calculations not just filling in a missing parameter.

class Pet:
    def __init__(self, name, age, type_):
        self.name = name
        self.age = age
        self.type_ = type_

    @classmethod
    def create_dog(cls, name, age):
        return cls(name, age, "dog")

    @classmethod
    def create_cat(cls, name, age):
        return cls(name, age, "cat")

cat = Pet.create_cat("marmaduke", 2)
dog = Pet.create_dog("loki", 4)

print(cat.name, "is a", cat.type_)
print(dog.name, "is a", dog.type_)

When the code is run you should get the pets name followed by what type the pet is (cat or dog).

marmaduke is a cat
loki is a dog

Research the @property decorator. This will allow control over set/get operations on variables.

Research

There is much more you can do with classes that is not going to be covered in this tutorial. Have a go and research about multi-inheritance once you understand all the content in this tutorial.

Multi-Inheritance is a cool feature in Python, a lot of languages do not have this functionality.

You could also research “dunder methods”. You already know one, that being: __init__.

There is a cool one called __repr__, that runs when you print a object

You could also look at private and protected attributes.