This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 6: Object methods

Instance methods

face Josiah Wang

You define methods pretty much just like defining functions, except:

  • you put them inside the scope of the class
  • the first parameter must be self
class Person:
    def __init__(self, name, age, nationality="uk"):
        self.name = name
        self.age = age
        self.nationality = nationality

    def introduce_self(self):
        print(f"Hey man! Name's {self.name}, from {self.nationality}!")

    def lie_about_age(self):
        print(f"I'm {self.age - 5} years old. Really.") 

    def emigrate(self, new_country):
        self.nationality = new_country

    def think_random_thought(self):
        return "Why is London called London?"


stranger = Person("Josiah", 20, "malaysia")

stranger.emigrate("uk")
stranger.introduce_self()
stranger.lie_about_age()

thought = stranger.think_random_thought()
print(thought)

And here is the output:

Hey man! Name's Josiah, from uk!
I'm 15 years old. Really.
Why is London called London?

Again, self basically points to the object itself (stranger in this example).

When you invoke a method (that’s how you formally ‘call’ a method), for example stranger.emigrate("uk"), Python will actually convert it to Person.emigrate(stranger, "uk") in the background. This is why there is no need to provide the first argument to self in the method call, because self refers to stranger.

stranger.emigrate("uk") will change stranger‘s nationality to "uk" (again, think of mutator methods like list.clear()). So when the stranger introduces himself in the next line, he says he’s from "uk" rather than "malaysia".

That’s really it about methods from an implementation standpoint!