DEV Community

sumandari
sumandari

Posted on

method (instance), @classmethod and @staticmethod

In a class we can have method, normal method without decorator. We also can have classmethod and staticmethod.

the normal method is a method that is bound to the instance. It has self as its first argument.
classmethod is bound to the class itself. It's usually used as a factory. It has cls as its first argument.
staticmethod is not bound to either instance or class. It's a general function and it doesn't have either self or cls as its argument.

>>> class Shape:
...     def __init__(self, name, height, width):
...         self.name = name
...         self.height = height
...         self.width = width
...     def __str__(self):
...         return f"shape: {self.name}, height: {self.height}, {self.width}"
...     @staticmethod
...     def area(height, width):
...         return height * width
...     @classmethod
...     def rectangular(cls):
...         return cls("rectangular", height, width)
...     @classmethod
...     def square(cls):
...         return cls("square", height, height)
Enter fullscreen mode Exit fullscreen mode

wait, is my code correct...?

Top comments (0)