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:

1class ClassName:
2    def method_name(self, parameters):
3        # Code to execute
4        ...

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:

1class Dog:
2    def bark(self):
3        print("Woof!")
4
5my_dog = Dog()
6my_dog.bark()  # prints: Woof!

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:

  1. 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.

  2. 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 and cls as the first parameter.

  3. 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.

 1class MyClass:
 2    class_var = "I'm a class variable"
 3
 4    def instance_method(self):
 5        return "I'm an instance method"
 6
 7    @classmethod
 8    def class_method(cls):
 9        return "I'm a class method"
10
11    @staticmethod
12    def static_method():
13        return "I'm a static method"

In the above example, instance_method, class_method, and static_method represent an instance method, class method, and static method, respectively.