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.py62 chars4 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.py32 chars3 lines
This will execute the code inside the method body.
gistlibby LogSnag