Methods¶
Functions on classes are called methods. Methods are functions bound to a
class. A constructor is also a method of the class. The constructor just has
a special name (__init__
).
The first argument of a method is named self
. It refers the the instance of
the class.
Note
The name self
is just a convention. Any name could be used, but just to stick
to self
and forget about that. Changing it to another name would just confuse
other developers.
class Person:
last_name = "Doe"
def __init__(self, first_name, age=None):
self.first_name = first_name
self.age = age
def who_am_i(self):
print(f"I am {self.first_name} {self.last_name}", end="")
if self.age:
print(f" and I am {self.age}.")
else:
print(".")
john = Person("John")
jack = Person("Jack", 33)
john.who_am_i() # prints out I am John Doe.
jack.who_am_i() # prints out I am Jack Doe and I am 33.