Methods
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
class Person:
def __init__(self, firstname, lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age = age
def greet(self, message):
print(f"{self.firstname} {self.lastname} says {message}!")
def get_fullname(self):
return f"{self.firstname} {self.lastname}"
person = Person("Josiah", "Wang", 20) # What do you mean I don't look 20? :D
person.greet("I love Machine Learning!")
print(person.get_fullname())
When you invoke person.get_fullname()
(Line 16), what happens in the background is that Python implicitly converts the call to Person.get_fullname(person)
. So self = person
. Obviously, you can call Person.get_fullname(person)
directly too, but let’s just keep it readable with a more convential OOP style method call, shall we?
Explicitly using self
for instance attributes and methods actually makes the code less ambiguous and more readable. This is in line with another 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.