Static & Instance Methods in Python Classes

In this article we want to learn about Static & Instance Methods in Python Classes, so Python is an object oriented programming language, using Python OOP you can work with classes and objects. in Python class is a blueprint for creating objects, and an object is an instance of a class. inside a class you can define methods that are used to manipulate data and perform operations. in Python there are two types of methods: static methods and instance methods.

 

 

Python Static Methods

First of all let’s talk about static methods,so static methods are methods that are related to a class not an instance of a class. they can be called without creating an instance of the class, and they do not operate on instance specific data. Static methods are declared using  @staticmethod decorator.

 

 

This is an example of static method in Python.

In the above  example my_static_method is a static method that takes two arguments, x and y, and returns their sum. this method is called directly on the class itself not on an instance of the class.

 

 

 

If you run the code this will be the result

Static & Instance Methods in Python Classes
Static & Instance Methods in Python Classes

 

 

 

Python Instance Methods

Instance methods are methods that belongs to an instance of a class. they operates on instance data, and they can only be called on an instance of the class. instance methods are declared like any other method.

 

 

This is an example of an instance method in Python:

In this example my_instance_method is an instance method that takes one argument y, and returns the sum of self.x and y. this method is called on an instance of the class my_object, which was created with an initial value of self.x = 3.

 

 

 

 

This will be the result

Python Instance Methods
Python Instance Methods

Subscribe and Get Free Video Courses & Articles in your Email

 

Leave a Comment

Share via
Copy link
Powered by Social Snap
×