add a method to a class in python

To add a method to a class in Python, we can define a function within the class definition. The function will become a method that can be called on instances of the class.

main.py
class MyClass:
    def my_method(self):
        # method body
62 chars
4 lines

In the example above, my_method is a method of the MyClass class. The self parameter is required for all instance methods and refers to the instance of the class on which the method is called.

We can then create an instance of the class and call the method on it:

main.py
obj = MyClass()
obj.my_method()
32 chars
3 lines

This will execute the code inside the method body.

related categories

gistlibby LogSnag