Instance methods
Source: Dev.to
Instance methods
After learning about classes, let’s learn about methods.
class Time:
def __init__(self):
self.hours = 0
self.minutes = 0
def print_time(self):
print(f'Hours: {self.hours}', end=' ')
print(f'Minutes: {self.minutes}')
time1 = Time()
time1.hours = 3
time1.minutes = 35
time1.print_time()
In the example above, print_time is an instance method—a function defined inside a class that operates on a particular instance.
The __init__ method is a special instance method that runs automatically when a new object is created, initializing its attributes.
A common mistake for beginners is to omit the self argument as the first parameter of a method. Because Python automatically passes the instance reference as the first argument, forgetting self leads to a “too many arguments” error.
Common error: forgetting self
class Employee:
def __init__(self):
self.wage = 0
self.hours_worked = 0
def calculate_pay(self): # `self` must be included
return self.wage * self.hours_worked
alice = Employee()
alice.wage = 6.25
alice.hours_worked = 15
print(f'Alice earned {alice.calculate_pay():.2f}')
If the self parameter is omitted (e.g., def calculate_pay():), calling alice.calculate_pay() will raise an error because Python tries to pass the instance automatically, resulting in a mismatch of arguments. Adding self resolves the issue.