In object-oriented programming, Python provides different types of methods to define the behavior of classes. Three commonly used methods are instance methods, class methods, and static methods. Such methods help us to create more organized and efficient code structures in Python.
Instance methods are the most common type of method in Python classes.
They are associated with objects (instances) of a class and are defined within the class definition.
Instance methods take the
selfparameter, which represents the instance itself.
They can access and modify instance variables and invoke other instance methods of the same class. To define an instance method, we use the
class Person: def instance_method(self, name, age): # Access instance variables self.name = name self.age = age # Creating an instance of MyClass obj = Person() # Calling the instance method obj.instance_method("Nirmal","23") print(obj.name, obj.age)# Output = Nirmal 23
In the example above,
instance_method() is an instance method that takes two arguments. It accesses the instance variables
arg2 using the
self parameter performs some operations and modifies the instance variables accordingly.
They can be called on the class itself to perform operations rather than instances.
Class methods take the
clsparameter, which represents the class itself.
We use the
@classmethoddecorator to define a class method.
Class methods are often used for alternative constructors.
class MyClass: class_variable = "Hello, World!" def class_method(cls): print("This is a class method.") print("Accessing class variable:", cls.class_variable) # Calling class method MyClass.class_method()
If we have nothing to do with instance and class then we use static method.
They are defined within the class definition using the
Static methods are not bound to the instance or the class, making them independent and self-contained.
class MyClass: def static_method(): print("This is a static method.") # Calling the static method MyClass.static_method()
This is a static method.