Methods
In the context of Python’s Object-Oriented Programming (OOP), methods are special functions that belong to a class, and therefore, to any object of that class. They allow us to manipulate an object’s attributes or to make it perform specific actions.
Method Definitions
The definition of methods is very similar to that of functions, with the notable difference that they must be defined inside a class. Below is an example syntax of a method:
In this syntax, method_name
is the name of the method, self
is a special parameter that references the instance of the class, and parameters
represent any additional parameters that the method requires.
Calling Methods
To call a method, we use the syntax object.method_name(parameters)
. Below is an example of method creation and calling:
In this example, we create a Dog
class with one method: bark
. Then we create an instance of the class and call its bark
method.
Note
The self
keyword is automatically passed by Python and does not need to be provided when calling the method.
Types of Methods
In Python OOP, there are three types of methods:
Instance Methods: These are the most common type. They can access and modify instance variables, and can also be used to call other instance methods.
Class Methods: These methods are shared among all instances of a class. They can’t access instance variables or methods, but they can access class variables. They are defined using the
@classmethod
decorator andcls
as the first parameter.Static Methods: These methods can’t access instance or class variables or methods. They work like regular functions but belong to the class’s namespace. They are defined using the
@staticmethod
decorator.
In the above example, instance_method
, class_method
, and static_method
represent an instance method, class method, and static method, respectively.