The procedure of creating methods inside the Python classes is similar to creating functions with the exception that inside the parenthesis of the method name we always have to put keyword self as the first argument. The general form of creating the method inside the class can be written in the following form.
Example 1 Create a class Rectangle that will calculate the area of the rectangle if the rectangle dimensions are 10 and 20 and 25 and 50, respectively.
Solution:
class ClassName:The methods are functions inside the class body. The definition of the method starts with def keyword followed by a space and the name of the method. After the method name, the set of parentheses is written which contains the argument/parameter list.
def MethodName(self):
pass
Important note The main difference between methods and functions is that all methods have required argument which is self argument. This argument to a method is a reference to the object that the method is being invoked on.
Example 1 Create a class Rectangle that will calculate the area of the rectangle if the rectangle dimensions are 10 and 20 and 25 and 50, respectively.
Solution:
class Rectangle:The output of Example 1.
def Area(self, a, b):
return self.a*self.b
Small = Rectangle()
Large = Rectangle()
Small.a = 10
Small.b = 20
Large.a = 25
Large.b = 50
print("Area of Small Rectangle = {}".format(Small.Area(Small.a, Small.b)))
print("Area of the Large Rectangle = {}".format(Large.Area(Large.a, Large.b)))
Area of Small Rectangle = 200
Area of the Large Rectangle = 1250