Methods are actuall functions inside a class that performs some operation by utilising the attributes of the object.
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
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