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.

Printing and __str__(self) method

If you want your cat objects to be printed in a certain way, you can define a __str__(self) method. By default, this method is defined in a way that just prints a class name and a hexidecimal memory address where the object is stored. If you want something other than that, you need to define your own version of __str__(self).

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

    def __str__(self):
        return "This cat is named " + self.name + "."

my_cat = Cat("Frank")
print(my_cat)