Methods in Python – A Key Concept of Object Oriented Programming

Overview

  • Methods in Python are a crucial concept to understand as a programmer and a data science professional
  • Here, we’ll talk about these different types of Methods in Python and how to implement the

Introduction

Python is a wonderful language but it can be daunting for a newcomer to master. Like any spoken language, Python requires us to first understand the basics before we can jump to building more diverse and broader applications in the data science field.

Here’s the thing – if you cover your basics well, you’ll find Python to be a breeze. But it’s crucial to spend the initial learning time familiarizing yourself with the features Python offers. It’ll really pay off in the long run!

Python is of course an Object-Oriented Programming (OOP) language. This is a wide concept and is not quite possible to grasp all at once. In fact, mastering OOP can take several months or even years. It totally depends upon your understanding capability. I highly recommend going through my previous article on the ‘Basic concepts of Object-Oriented Programming‘ first.

So in this particular article, I’ll expand the concept of methods in Object-Oriented Programming further. We’ll talk about the different types of Methods in Python. Since python Methods can be confusing sometimes if you are new to OOP, I’ll cover methods in Python and their types in detail in this article. And then we’ll see the use cases of these methods.

But wait – what are Python methods? Well, let’s begin and find out!

If you’re completely new to Python, you should check out this free Python course that’ll teach you everything you need to get started in the data science world.

Table of Contents

  • What are Methods in Python?
  • Types of Methods in Python
    • Instance methods
    • Class methods
    • Static methods
  • When to use Which type of Python Method?

What are Methods in Python?

The big question!

In Object-Oriented Programming, we have (drum roll please) objects. These objects consist of properties and behavior. Furthermore, properties of the object are defined by the attributes and the behavior is defined using methods. These methods are defined inside a class. These methods are the reusable piece of code that can be invoked/called at any point in the program.

Python offers various types of these methods. These are crucial to becoming an efficient programmer and consequently are useful for a data science professional.

Types of Methods in Python

There are basically three types of methods in Python:

  • Instance Method
  • Class Method
  • Static Method

Let’s talk about each method in detail.

Instance Methods

The purpose of instance methods is to set or get details about instances (objects), and that is why they’re known as instance methods. They are the most common type of methods used in a Python class.

They have one default parameter- self, which points to an instance of the class. Although you don’t have to pass that every time. You can change the name of this parameter but it is better to stick to the convention i.e self.

Any method you create inside a class is an instance method unless you specially specify Python otherwise. Let’s see how to create an instance method:

class My_class:
  def instance_method(self):
    return "This is an instance method."

It’s as simple as that!

In order to call an instance method, you’ve to create an object/instance of the class. With the help of this object, you can access any method of the class.

obj = My_class()
obj.instance_method()

Methods In Python - Instance Method

When the instance method is called, Python replaces the self argument with the instance object, obj. That is why we should add one default parameter while defining the instance methods. Notice that when instance_method() is called, you don’t have to pass self.  Python does this for you.

Along with the default parameter self, you can add other parameters of your choice as well:

class My_class:

  def instance_method(self, a):
    return f"This is an instance method with a parameter a = {a}."

We have an additional parameter “a” here. Now let’s create the object of the class and call this instance method:

obj = My_class()
obj.instance_method(10)

Methods In Python

Again you can see we have not passed ‘self’ as an argument, Python does that for us. But have to mention other arguments, in this case, it is just one. So we have passed 10 as the value of “a”.

You can use “self” inside an instance method for accessing the other attributes and methods of the same class:

class My_class:

  def __init__(self, a, b):
    self.a = a
    self.b = b

  def instance_method(self):
    return f"This is the instance method and it can access the variables a = {self.a} and
 b = {self.b} with the help of self."

Note that the __init__() method is a special type of method known as a constructor. This method is called when an object is created from the class and it allows the class to initialize the attributes of a class.

obj = My_class(2,4)
obj.instance_method()

Methods In Python

With the help of the “self” keyword- self.a and self.b, we have accessed the variables present in the __init__() method of the same class.

Along with the objects of a class, an instance method can access the class itself with the help of self.__class__ attribute. Let’s see how:

class My_class():

  def instance_method(self):
    print("Hello! from %s" % self.__class__.__name__)

obj = My_class()
obj.instance_method()

Methods In Python

The self.__class__.__name__ attribute returns the name of the class to which class instance(self) is related.

2. Class Methods

The purpose of the class methods is to set or get the details (status) of the class. That is why they are known as class methods. They can’t access or modify specific instance data. They are bound to the class instead of their objects. Two important things about class methods:

  • In order to define a class method, you have to specify that it is a class method with the help of the @classmethod decorator
  • Class methods also take one default parameter- cls, which points to the class. Again, this not mandatory to name the default parameter “cls”. But it is always better to go with the conventions

Now let’s look at how to create class methods:

class My_class:

  @classmethod
  def class_method(cls):
    return "This is a class method."

As simple as that!

As I said earlier, with the help of the instance of the class, you can access any method. So we’ll create the instance of this My_class as well and try calling this class_method():

obj = My_class()
obj.class_method()

Methods In Python

This works too! We can access the class methods with the help of a class instance/object. But we can access the class methods directly without creating an instance or object of the class. Let’s see how:

My_class.class_method()

Methods In Python

Without creating an instance of the class, you can call the class method with – Class_name.Method_name().

But this is not possible with instance methods where we have to create an instance of the class in order to call instance methods. Let’s see what happens when we try to call the instance method directly:

My_class.instance_method()

Methods In Python - Error

We got an error stating missing one positional argument – “self”.  And it is obvious because instance methods accept an instance of the class as the default parameter. And you are not providing any instance as an argument. Though this can be bypassing the object name as the argument:

My_class.instance_method(obj)

Awesome!

3. Static Methods

Static methods cannot access the class data. In other words, they do not need to access the class data. They are self-sufficient and can work on their own.  Since they are not attached to any class attribute, they cannot get or set the instance state or class state.

In order to define a static method, we can use the @staticmethod decorator (in a similar way we used @classmethod decorator). Unlike instance methods and class methods, we do not need to pass any special or default parameters. Let’s look at the implementation:

class My_class:

  @staticmethod
  def static_method():
    return "This is a static method."

And done!

Notice that we do not have any default parameter in this case. Now how do we call static methods? Again, we can call them using object/instance of the class as:

obj = My_class()
obj.static_method()

And we can call static methods directly, without creating an object/instance of the class:

My_class.static_method()

You can notice the output is the same using both ways of calling static methods.

Here’s a summary of the explanation we’ve seen:

    • An instance method knows its instance (and from that, it’s class)
    • A class method knows its class
    • A static method doesn’t know its class or instance

When to Use Which Python Method?

The instance methods are the most commonly used methods. Even then there is difficulty in knowing when you can use class methods or static methods. The following explanation will satiate your curiosity:

Class Method – The most common use of the class methods is for creating factory methods. Factory methods are those methods that return a class object (like a constructor) for different use cases. Let’s understand this using the given example:

from datetime import date

class Dog:
  def __init__(self, name, age):
    self.name = name
    self.age = age

# a class method to create a Dog object with birth year.
  @classmethod
  def Year(cls, name, year):
    return cls(name, date.today().year - year)

Here as you can see, the class method is modifying the status of the class. If we have the year of birth of any dog instead of the age, then with the help of this method we can modify the attributes of the class.

Let’s check this:

Dog1 = Dog('Bruno', 1)
Dog1.name , Dog1.age

Here we have constructed an object of the class. This takes two parameters name and age. On printing the attributes of the class we get Bruno and 1 as output, which was the values we provided.

Dog2 = Dog.Year('Dobby', 2017)
Dog2.name , Dog2.age

Here, we have constructed another object of the class Dog using the class method Year(). The Year() method takes Person class as the first parameter cls and returns the constructor by calling cls(name, date.today().year – year), which is equivalent to Dog(name, date.today().year – year).

As you can see in printing the attributes name and age we got the name that we provided and the age converted from the year of birth using the class method.

Static Method – They are used for creating utility functions. For accomplishing routine programming tasks we use utility functions. A simple example could be:

class Calculator:
 
  @staticmethod
  def add(x, y):
    return x + y

print('The sum is:', Calculator.add(15, 10))

You can see that the use-case of this static method is very clear, adding the two numbers given as parameters. Whenever you have to add two numbers, you can call this method directly without worrying about object construction.

End Notes

In this article, we learned about Python methods, types of methods and saw how to implement each method.

I recommend you go through these resources on Object-Oriented Programming-

Let me know in the comments section below if you have any queries or feedback. Happy learning!

Author: admin

Leave a Reply

Your email address will not be published.