This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Defining methods

Objects can also have methods, which is something that an object can do.

Methods are often actions, so like functions, they will often end up being verbs.

For example, a person can speak, walk, run, study, or cry.

You define methods pretty much just like defining functions, but inside the scope of the class, and the first parameter must be self.

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

    def introduce_self(self):
        print("Hello! My name is {self.name}.")

    def lie_about_age(self):
        print("I am {self.age - 5} years old.")

lecturer = Person("Josiah", 20)
lecturer.introduce_self()
lecturer.lie_about_age()

In the example above, when the method lecturer.introduce_self() is invoked (that’s how you ‘call’ a method), Python will actually convert it to Person.introduce_self(lecturer) in the background. This is why there is no need to provide the first argument to self, because it refers to lecturer.

Class methods

Like attributes, you can also have method that belongs only to the class (and not the class instance).

Such class methods does not receive the instance to the class (self) as the first argument, but instead takes the class itself (cls).

Thus, like class attributes, class methods do not have access to the object instance, but only the class.

You will also need to provide a decorator @classmethod to indicate that it is a class method.

class Person:
    count = 0
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
        Person.count += 1

    @classmethod
    def get_population(cls):
        return cls.count

print(Person.get_population)

A possible use case for class methods is to create new instances of the class using the Factory method. (This is a completely advanced topic in the field of Design Patterns in OOP. You do not need to know this!)

from datetime import date

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

   @classmethod
   def create_from_birth_year(cls, name, birth_year):
      return cls(name, date.today().year - birth_year)

singer = Person.create_from_birth_year("Celine Dion", 1968)
print(singer.name)
print(singer.age)