Methods in Python: a key concept of object-oriented programming

Contents

Overview

  • Methods in Python are a crucial concept to understand as a programmer and data science professional..
  • Here, We will talk about these different types of methods in Python and how to implement the

Introduction

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

Here is the question: if you cover your basics well, you will find python very straightforward. But it is crucial to spend the initial learning time to become familiar with the functions that Python offers.. It will really pay off in the long run!!

types-of-methods-in-python-9192148

Python it, of course, an object-oriented programming language (OOP). This is a broad concept and it is not possible to understand it all at once.. In fact, mastering object-oriented programming can take several months or even years. It totally depends on your ability to understand. I highly recommend reading my previous article on the 'Basics of Object Oriented Programming' first..

Then, in this particular article, I will further expand the concept of methods in Object Oriented Programming. We will talk about the different types of methods in Python. Since Python methods can be confusing at times if you are new to OOP, I will cover the methods in Python and their types in detail in this article. And then we will see the use cases of these methods.

But wait, What are python methods? Good, Let's get started and discover!

If you are completely new to Python, you should check this free python course that will teach you everything you need to get started in the world of data science.

Table of Contents

  • What are the methods in Python?
  • Types of methods in Python
    • Instance methods
    • Class methods
    • Static methods
  • When to use What kind of Python method?

What are the methods in Python?

The great question!

In Object Oriented Programming, we have objects (drum roll, please). These objects consist of properties and behavior. What's more, object properties are defined by attributes and behavior is defined by methods. These methods are defined within a class. These methods are the reusable code snippet that can be invoked / call at any point in the program.

Python offers several 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

Basically, There are 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 drill down on instances (objects), and that is why they are known as instance methods. They are the most common type of method used in a Python class.

They have a default parameter: oneself, which points to an instance of the class. You don't have to go through that all the time though. You can change the name of this parameter, but you better stick to convention, namely oneself.

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!

To call an instance method, must create an object / class instance. With the help of this object, can access any method of the class.

obj = My_class()
obj.instance_method()

screenshot-from-2020-10-19-10-03-00-3996945

When the instance method is called, Python replaces the oneself argument with the instance object, obj. That is why we need to add a default parameter when defining the instance methods. Notice that when instance_method () is named, does not have to happen to itself. Python does this for you.

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

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 class object and call this instance method:

obj = My_class()
obj.instance_method(10)

screenshot-from-2020-10-19-10-05-07-6742157

Again, you can see we haven't passed 'self’ as an argument, Python does it for us. But there are other arguments to be mentioned, in this case, it's only one. So we have passed 10 as value of “a”.

You can use “self” inside an instance method to access 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 than the __init __ method () is a special type of method known as constructor. This method is called when an object is created from the class and allows the class to initialize the attributes of a class.

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

screenshot-from-2020-10-19-10-06-26-6642977

Let's try this code in the live encoding window below.

With the help of the keyword "self" 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 I .__ 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()

screenshot-from-2020-10-19-10-08-29-4298856

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

2. Class methods

The purpose of the class methods is to set or get the details (condition) of the class. That is why they are known as class methods. They cannot access or modify specific instance data. They are bound to the class rather than its objects. Two important things about class methods:

  • To define a class method, You must specify that it is a class method with the help of the @classmethod decorator
  • Class methods also take a default parameter: cls, that points to the class. Again, this is not required to name the default parameter “cls”. But it is always better to go with the conventions

Now let's see 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 before, with the help of the class instance, can access any method. So we will instantiate this My_class as well and try to call this class_method ():

obj = My_class()
obj.class_method()

screenshot-from-2020-10-19-10-09-19-4759548

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

screenshot-from-2020-10-19-10-09-19-4759548

Without instantiating the class, you can call the class method with – Cclass_name.method_name ().

But this is not possible with the instance methods where we have to instantiate the class to call the instance methods. Let's see what happens when we try to call the instance method directly:

My_class.instance_method()

screenshot-from-2020-10-19-10-11-15-9970810

We have an error indicating that a positional argument is missing: “me”. And it's obvious because instance methods accept an instance of the class as a default parameter. And it does not provide any instance as an argument. Although this may ignore the object name as an argument:

My_class.instance_method(obj)

screenshot-from-2020-10-19-10-03-00-3996945

Impressive!

3. Static methods

Static methods cannot access class data. In other words, they don't need to access the class data. They are self-sufficient and can work alone. Since they are not attached to any class attributes, cannot get or set instance state or class state.

To define a static method, we can use the @staticmethod decorator (similarly we use the @classmethod decorator). Unlike instance and class methods, we don't need to pass any special or default parameters. Let's see the implementation:

class My_class:

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

And done!

Note that we do not have any default parameters in this case. However, How do we call static methods? Again, we can call them using the object / class instance like:

obj = My_class()
obj.static_method()

screenshot-from-2020-10-19-10-13-22-4953073

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

screenshot-from-2020-10-19-10-13-22-4953073

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

Here is a summary of the explanation we have seen:

    • An instance method knows its instance (and from that, his class)
    • A class method knows its class
    • A static method does not know its class or instance

When to use which Python method?

Instance methods are the most used methods. Even then, it's hard to tell when you can use class methods or static methods. The following explanation will satisfy your curiosity:

Class method – The most common use of class methods is to create factory methods. Factory methods are those methods that return a class object (like a builder) 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 state 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
screenshot-from-2020-10-19-10-14-14-4460244

Here we have constructed an object of the class. This takes the name and age of two parameters. By printing the attributes of the class we get Bruno and 1 as a way out, what were the values ​​we provided.

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

screenshot-from-2020-10-19-10-15-07-9260481

Here, we have built another object of the class Dog using the method of the class. Year(). The Year method () take Person class as first parameter cls and returns the constructor by calling cls (Name, fecha.today (). year – year), which is equivalent to Dog (Name, today `s date (). Year – year).

As you can see by printing the attribute name and age, we got the name we provided and the age converted from the year of birth using the class method.

Static method – They are used to create utility functions. To perform routine programming tasks, we use utility functions. A simple example could be:

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

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

screenshot-from-2020-10-19-10-15-47-8126031

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

Final notes

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

I recommend that you review these resources on object-oriented programming:

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

Subscribe to our Newsletter

We will not send you SPAM mail. We hate it as much as you.