How#

How to define a class#

We define a class using the class keyword:

Tip

class Name:
    """
    A docstring between triple quotation to describe what the class represents
    """
    INDENTED BLOCKS OF CODE

For example to create a class for a country:

class Country:
    """
    A class to represent a country
    """

How to create an instance of the class#

Once a class is defined we call it using the ():

Tip

Name()

For example:

first_country = Country()
first_country
<__main__.Country at 0x7f22a8f76e00>
second_country = Country()
second_country
<__main__.Country at 0x7f22a8f76e30>

The at … is a pointer to the location of the instance in memory. If you re run the code that location will change.

How to create an attribute#

Attributes are variables that belong to instances of classes. There can be created and accessed using .name_of_variable.

For example, the following creates the attributes:

first_country.name = "Narnia"
first_country.amount_of_magic = 500

We can access them:

first_country.name
'Narnia'
first_country.amount_of_magic
500

We can manipulate them in place:

first_country.amount_of_magic += 100
first_country.amount_of_magic
600

How to create and call a method#

Methods are functions that belong to classes. We define a function using the def keyword (short for define). The first variable of a method is always the specific instance that will call the method (it is passed implicitly).

Tip

class Name:
    """
    A docstring between triple quotation to describe what the class represents
    """
    def name(self, parameter1, parameter2, …):
        """
        <A description of what the method is.>

        Parameters
        ----------
        parameter1 : <type of parameter1>
            <description of parameter1>
        parameter2 : <type of parameter2>
            <description of parameter2>
        ...

        Returns
        -------
        <type of what the function returns>
            <description of what the function returns>

        """
        INDENTED BLOCK OF CODE
        return output

For example let us create a class for a country that has the ability to “spend” magic:

class Country:
    """
    A class to represent a country
    """

    def spend_magic(self, amount_spent):
        """
        Updates the magic attribute by subtracting amount_spent

        Parameters
        ----------
        amount_spent : float
            The amount of mana used.
        """
        self.amount_of_magic -= amount_spent

Now we can use it:

first_country = Country()
first_country.name = "Narnia"
first_country.amount_of_magic = 500
first_country.spend_magic(amount_spent=100)
first_country.amount_of_magic
400

Attention

Even though the method is defined as taking two variables as inputs: self and amount_spent we only have to explicitly pass it amount_spent. The first variable in a method definition always corresponds to the instance on which the method exists.

How to create and call magic methods#

Some methods can be called in certain situations:

  • When creating an instance.

  • When wanting to display an instance.

This are referred to as dunder methods as they are all in between two underscores: __.

The method that is called when an instance is created is called __init__ (for initialised). For example:

class Country:
    """
    A class to represent a country
    """

    def __init__(self, name, amount_of_magic):
        self.name = name
        self.amount_of_magic = amount_of_magic

Now instead of creating an instance and then creating the attributes we can do those two things at the same time, by passing the variables to the class itself (which in turn passes them to the __init__ method):

first_country = Country("Narnia", 500)
first_country.name
'Narnia'
first_country.amount_of_magic
500

The method that returns a representation of an instance is __repr__. For example:

class Country:
    """
    A class to represent a country
    """

    def __init__(self, name, amount_of_magic):
        self.name = name
        self.amount_of_magic = amount_of_magic

    def __repr__(self):
        """Returns a string representation of the instance"""
        return f"{self.name} with {self.amount_of_magic} magic."
first_country = Country("Narnia", 500)
first_country
Narnia with 500 magic.

There are numerous other magic methods, such as the __add__ one used in Tutorial.

How to use inheritance#

Inheritance is a tool that allows us to create one class based on another. This is done by passing the Old class to the New class.

Tip

class New(Old)

For example let us create a class of MuggleCountry that overwrites the __init__ method but keeps the __rep__ method of the Country class written in How to create and call magic methods:

class MuggleCountry(Country):
    """
    A class to represent a country with no magic. It only requires the name on
    initialisation.
    """

    def __init__(self, name):
        self.name = name
        self.amount_of_magic = 0

This has replaced the __init__ method but the __repr__ method is the same:

other_country = MuggleCountry("Wales")
other_country
Wales with 0 magic.