Object Methods

A method is a function that belongs to an object.


Methods are declared inside the class declaration.

This means the def statement is indented one level inside the class, and the method’s code block  is indented two levels inside the class.

class Cat:
    def meow(self):
        print('A cat meows.')
        print('Meow!')

    def sleep(self):
        print('Zzzzzzzzz...')

Now we can a Cat object and call their methods:

my_cat = Cat()
my_cat.meow()
my_cat.sleep()

This might be more interesting if we had multiple cats with names. We’ll update the methods to print the name of the cat:

class Cat:
    def __init__(self, n):
        self.name = n

    def meow(self):
        print(self.name, 'meows.')
        print('Meow!')

    def sleep(self):
        print(self.name, 'is sleeping.')
        print('Zzzzzzzzz...')

Bonus: the Cat class now has an __init__(self) method that lets you input the cat’s name when it’s created.

Creating cats which subsequently meow:

my_cat = Cat('Fat Cat')
cat2 = Cat('Meatball')
cat3 = Cat('Potato')

my_cat.meow()
cat2.meow()
cat3.meow()

What is self?

The word self only appears in the class declaration. Class methods need to work for any object of that type, so they have to be generic. To have an object refer to itself, use the word self instead of the name of a particular object.

All of the method declarations include self as the first argument. This means the object has access to itself, including all of its own attributes and methods, within the scope of the method.

Let’s examine the new meow(self) method:

    def meow(self):
        print(self.name, 'meows.')

When my_cat calls its meow() method, self.name refers to my_cat.name.