Chapter 8: Object-oriented programming

Methods

face Josiah Wang

Methods in Python are just like functions. The only main difference is that the first parameter in the method definition must take a reference to the object instance (i.e. self). This will allow you to access the properties of the instance inside the method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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)

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

When you invoke 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. Obviously, you can call Person.emigrate(stranger, "uk") directly too, but let’s just keep it readable with a more conventional OOP style method call, shall we?

Explicitly using self for instance attributes and methods actually makes the code less ambiguous and more readable. In fact, you MUST explicitly use self. Remember one of Python’s design philosophy: “explicit is better than implicit”. Compare this to Java where you do not always need to use the this keyword unless it is ambiguous.