DEV Community 👩‍💻👨‍💻

Charles Ukadike
Charles Ukadike

Posted on

Classmethod vs Staticmethod in Python's OOP

A little code written to understand classmethod and staticmethod

class Area: #defining an area class
def init(self,wt,ht): ht
self.wt= wt
def area(self): #defining a simple rect area method
return self.wt*

def sqr(cls,sd): #defining a square method to take advantage of the rect area method
    return cls(sd,sd)
Enter fullscreen mode Exit fullscreen mode

class Tri(Area): #defining a triangle class to inherit from the area class
def area(self):
super().area() #calling the rect area method from the super_class "Area"
return int(0.5*self.wt* #using the super_class's argument to output the triangle's area
def check(var): #defining a regular function
if var>=20:
print("This triangle has a large area")
print("Small area detected")

rect= Area(4,5)
sqr= Area.sqr(7) #initiating the square's area
tri= Tri(30,100)

Tri.check(tri.area()) #calling the regular function (initiating the staticmethod). This takes the format: class.method()

tri.check(tri.area()) the above can also be written this way. This takes the format: object.method()


Note 01: To initiate a classmethod or call a staticmethod; the format is as follows "class.method()"

Note 02: To initiate / call other methods or staticmethod, the format is as follows; "object.method()"

Note 03: Note that staticmethods can be called in 2 ways;

By class e.g class.method()

By object e.g object.method()

Top comments (1)

citronbrick profile image

Please use formatting, including for your code

Very useful article though.

We want your help! Become a Tag Moderator.
Check out this survey and help us moderate our community by becoming a tag moderator here at DEV.