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...?

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post