Class Methods
Methods are functions defined inside the body of a class. They are performed operations with the attributes of our objects.
Methods are essential in the encapsulation concept of the OOP paradigm. For example, we might have a connect method in our ConnectDatabase
class. We need not be informed how exactly the method connects to the database. We only know that it is used to connect to a database. This is essential in dividing responsibilities in programming, especially in large applications.
In the code example, we have a Circle class
. We define three new methods.
The area method returns the area of a circle.
The setRadius
method sets a new value for the radius attribute.
The getRadius
method returns the current radius.
The method is called on an instance object. The c
object is paired with the self parameter of the class definition. The number 5
is paired with the radius parameter.
In Python, we can call methods in two ways. There are bounded and unbounded method calls.
In this example, we demonstrate both method calls.
This is the bounded method call. The Python interpreter automatically pairs the m
instance with the self parameter.
And this is the unbounded method call. The instance object is explicitly given to the getName
method.
Last updated