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.
1 2 3 4 5 6 7 |
class MyClass: @staticmethod def my_static_method(x, y): return x + y result = MyClass.my_static_method(4, 7) print(result) |
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
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:
1 2 3 4 5 6 7 8 9 10 |
class MyClass: def __init__(self, x): self.x = x def my_instance_method(self, y): return self.x + y my_object = MyClass(3) result = my_object.my_instance_method(4) print(result) |
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
Subscribe and Get Free Video Courses & Articles in your Email