Instance methods
After learning about classes, lets 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; We have said a function defined within a class is a method. The function print_time becomes an instance method in our example. In our code example above, we have another method. the init method of the Time class. The init is a special method name,that indicates that the method implements some special behavior of the class. init has a apecial behaviour which is the initialization of new instances. A common error for new programmers is to omit the self argument as the first parameter of a method. In such cases, calling the method produces an error indicating too many arguments were given by the programmer, because a method call automatically inserts an instance reference as the first argument. Example class Employee: def __init__(self): self.wage = 0 self.hours_worked = 0 def calculate_pay(): # missing self parameter return self.wage * self.hours_worked alice = Employee() alice.wage = 6.25 alice.hours_worked = 15 print(f'Alice earned {alice.calculate_pay():.2f}') The programme above will give an error when we try to execute it. This is because we did not pass the self parameter.
