Python — Different Types of Methods
This is frequent question in interviews, they will ask us to explain about method and type of methods in Python. lets have a quick read about them.
In Python, you can define three types of methods in a class: instance methods, class methods, and static methods. Each type of method serves a different purpose. Here are examples of each type of method:
Instance Method:
- Instance methods are the most common type of methods in Python classes.
- They operate on the instance’s attributes and can modify or access instance-specific data.
In this example, the greet
method is an instance method because it operates on the self
object, which is a specific instance of the Person
class.
Class Method:
- Class methods are used for operations that are not specific to an instance but relate to the class itself.
- They are defined with the
@classmethod
decorator and take the class (usually namedcls
) as their first parameter.
In this example, the from_diameter
method is a class method because it's not bound to any specific instance but relates to the Circle
class.
Static Method:
- Static methods are used for utility functions that don’t depend on instance-specific or class-specific data.
- They are defined with the
@staticmethod
decorator and do not take theself
orcls
parameter by convention.
In this example, both the add
and multiply
methods are static methods because they don't depend on any instance-specific or class-specific data.
Understanding these three types of methods in Python classes is crucial for structuring your code effectively and efficiently, as each type serves a distinct purpose.