Classes

Python classes are a way of encapsulating chunks of functionality that belong together. You might not be aware of it but we've been using classes for a while. Python lists, dictionaries and many other data structures are implemented as classes.

Let's define a class that generates bad bird calls to explore how classes work. Note that functions associated with a class are known as methods.


In [1]:
class BirdCallGenerator:
        
    def __init__(self, bird_name, time_of_day = "noon"):
        self.bird_name = bird_name
        self.time_of_day = time_of_day   

    def custom(self, sound):
        return "The " + self.bird_name + " went " + sound + " at " + self.time_of_day
    
    def tweet(self):
        return self.custom("tweet")

There's a lot going on here but let's work through it. The __init__ method is used to create instances of the class. However you don't call it directly, but rather through the name of the class as follows.


In [2]:
magpie = BirdCallGenerator("Magpie")
heron = BirdCallGenerator("Heron", "dawn")

magpie and heron are instances of the class.


In [3]:
print(magpie)
print(heron)


<__main__.BirdCallGenerator instance at 0x7f790cd97290>
<__main__.BirdCallGenerator instance at 0x7f790cd973b0>

Calling the tweet method works as follows


In [4]:
magpie.tweet()


Out[4]:
'The Magpie went tweet at noon'

Notice how tweet doesn't take an argument even though it is defined as

def tweet(self)

In fact notice how the first parameter of every method in the class starts with self. This is an implicit paramenter that represent the instance of the class itself. Notice how in the tweet method, the custom method is called using self.custom.

Accessing the fields bird_name and time_of_day works much the same way. Accessing them outside of the class works as follows:


In [5]:
magpie.bird_name


Out[5]:
'Magpie'

Each class encapsulates the information it was given when constructed. Look at how the tweet of the heron is different.


In [6]:
heron.tweet()


Out[6]:
'The Heron went tweet at dawn'