What is Static & Instance Methods in Python Classes and Objects

In this Python Classes and Objects article we want to learn that What is Static & Instance Methods in Python Classes and Objects, so Python is an object oriented programming language that allows you to  work with classes and objects. so 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.

 

 

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

What is Static & Instance Methods in Python Classes and Objects
What is Static & Instance Methods in Python Classes and Objects

 

 

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 Method
Python Instance Method

 

 

Learn More

Leave a Comment