Previous: Protected Attributes & Private Attributes

Static method is the method defined inside the class that does not take self or cls as the first parameter. Because of that, Static method can be placed outside the class as a standalone function.

# What is the difference between def displayClassName1(self)
# and def displayClassName2() in this code?
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    def displayClassName1(self):
        print('Rectangle')

    def displayClassName2():
        print('Rectangle')

rectangle = Rectangle(10, 5)
rectangle.displayClassName1()
rectangle.displayClassName2()

Output:

Traceback (most recent call last):
  File "/Users/macbook/Documents/Code Python/Practice/Practice - ObjectOriented/Sample.py", line 17, in <module>
    rectangle.displayClassName2()
TypeError: Rectangle.displayClassName2() takes 0 positional arguments but 1 was given
Rectangle

The TypeError occurs because when rectangle.displayClassName2() is called, implicitly passes the instance (rectangle) as the first argument, but the method is not expecting any arguments.

This method, rectangle.displayClassName1(self), calls the method that correctly includes self, making it an instance method that can access the instance attributes and be called on an object.

<aside> 💡

The method that does not take self or cls as the first parameter in the class should be made a static method.

</aside>

Imagine that we want to have a function that receives the width and height values of a rectangle and returns the calculated area?

Take advantage of the Rectangle class to code this new function.

# Static Method - does not take self as the first parameter
class Rectangle:
    def __init__(self, width, length):
        # Private attributes
        self.__width = width
        self.__length = length
        
    @property
    def Width(self):
        return self.__width

    @property
    def Length(self):
        return self.__length

    @staticmethod
    def calculate_area(width, length):
        return width * length

def main():
    rect = Rectangle(12, 15)
    print(rect.calculate_area(rect.Width, rect.Length))

main()

Output:

180

Create an instance of the Rectangle class with the width and height received as parameters and return the result of the call to the calculate_area() function. Remember that we don't have to worry about releasing the resources required by the Rectangle instance, because the reference count for this object will become 0 after the function returns the result.