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 methods 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.
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 in Python are defined inside a class. These methods are the reusable piece of code that can be invoked/called at any point in the program.
In Python, methods are functions that are associated with an object and can manipulate its data or perform actions on it. They are called using dot notation, with the object name followed by a period and the method name. Methods are an important part of object-oriented programming in Python.
Python offers various types of these methods. These are crucial to becoming an efficient programmer and consequently are useful for a data science professional.
There are basically three types of methods in Python:
Let’s talk about each method in detail.
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()
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)
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()
Let’s try this code in the live coding window below.
# define the 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."
obj = My_class(2,4)
print(obj.instance_method())
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()
The self.__class__.__name__ attribute returns the name of the class to which class instance(self) is related.
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:
Now let’s look at how to create class methods:
class My_class:
@classmethod
def class_method(cls):
return "This is a class method."
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:
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()
My_class.class_method()
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()
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!
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:
In Python, a method is a unique kind of function that is created inside a class and is linked to certain objects generated from that class. Techniques can execute tasks or functions on these entities, like changing their condition or providing data about them. On the flip side, attributes are data components that pertain to an object and elucidate its qualities or traits.
A Python method list is a list that holds functions that are defined within a class, known as methods. These techniques are intended to function on instances formed from that category. Upon creation, an object has the ability to utilize the methods within its class for carrying out different functions or activities.
In Python, a method is a function created inside a class and linked to objects made from that class. Techniques are employed to carry out tasks on these entities, like altering their condition or giving details about them. In Python, an object is a class instance with methods and attributes linked to it.
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.
In this article, Python methods are functions associated with objects, categorized into instance, class, and static methods. They allow manipulation and interaction with object data. Attributes describe object characteristics. Method lists contain functions within classes for specific object operations. Understanding methods and attributes in Python aids effective object-oriented programming.
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!
Excellent article. It was great help for me. Thousands thanks.
Glad to help!
Great. Thanks for your article. Please, are you able to write on Iterators, Iterables and Generators in Python.
Hi Olu! I'm glad you liked my blog. You can read about Iterables and Generators from here, we already have a blog on this topic - https://www.analyticsvidhya.com/blog/2020/05/python-iterators-and-generators/
Thanks for sharing this Article.
Thank you! Happy to help.