DEV Community

M.Ark
M.Ark

Posted on

Instance methods

After learning about classes, lets learn about methods.
An instance method is a function defined within a class. It can be referenced using a dot notation.
Here is an example.

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()

Enter fullscreen mode Exit fullscreen mode

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.
The definition of print_time() has a self parameter the provides a reference to the class instance.
In our example above, the parameter self is bound to time1, when time1.print_time() is called.
The method's code can use "self" to access other attributes or methods of the instance. Example: The print_time method uses "self.hours" and "self.minutes" to get the value of the time1 instance data attributes.

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.
Special methods can always be identified be the double underscores(__) that appear before and after an identifier.

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}')
Enter fullscreen mode Exit fullscreen mode

The programme above will give an error when we try to execute it. This is because we did not pass the self parameter.

Top comments (0)