Thursday, October 6, 2016

[ Objected-Oriented Programming ] Class & Static Methods

Instance of a class 

  • passed to the self parameter of the method

Class methods

  • called by a class, which is passed to the cls parameter of the method
>>>
class Rectangle:
  def__init__(self,width,height):
    self.width = width
    self.height = height

  def calculate_area(self)
    return self.width*self.height


  @classmethod
  def new_square(cls, side_length):
    return cls(side_length , side_length)


square = Recangle.new_square(5)
print(square.calculate_area())


>>>
25

new_square is a class method and is called on the class , rather than on an instance of the class.It returns a new object of the class cls.


Static methods
  • similar to class method ,except they don;t receive any additional arguments
  • behave like plain fuction
  • @staticmethod

No comments:

Post a Comment