Methods In OOP

Methods are actuall functions inside a class that performs some operation by utilising the attributes of the object.

Note that while getting the value of an argument from a class , we were not using parenthesis() simply because it is just an information and there is no operation to be performed , however when calling a method of an object , you have to use () to invoke the method.

A class can have multiple methods associated with it. There is no restriction on the number of methods inside a class.

let us look at an example where we have square as our object and a method that returns its area.

class square():    def __init__(self,side_length):      self.side_length = side_length         #methods must contain self key word      def Area(self):      return self.side_length**2        my_square = square(5)  print(my_square.Area())

output:
25

It is possible for an method to accecpt external parameters without being linked to the ‘self’ keyword.

In our square object , instead of passing the side_length to our class , we can pass it simply to the Area method. The code becomes something like this:

class square():    def __init__(self):        # to avoid syntax error use pass        pass         #methods must contain self key word     #self has to be used , even if you are not using it    def Area(self,side_length):      return side_length**2        my_square = square()  print(my_square.Area(5))

output:
25

We can also assign a default value to a parameter( like we did in functions ) for methods in the class. If the value for that parameter is not passed then it’s default value will be used but if a value is passed, then the default value will be overwritten. Let us take an example on this.

class square():    def __init__(self,side_length = 2):      self.side_length = side_length         #methods must contain self key word      def Area(self):      return self.side_length**2        # no value is passed      my_square = square()  print(my_square.Area())    # value is passed  my_square = square(10)  print(my_square.Area())

output:
4  100