+ 1

Need better explanation of class- and static- methods

Hi! I tried to understand how classmethods and staticmethods works, but I can't get it. Could someone explain it to me? Or do you have any good explanation on youtube or something? Thank you! PS. I'm from Poland, so if you're polish too, I'd be very thankful for polish explanation.

2nd Jul 2017, 7:32 PM
Batman1910
Batman1910 - avatar
2 ответов
+ 6
Classmethods, marked with the @classmethod decorator, are kind of "picklocks" for modifying normal class behaviour, particularly its regular __init__ behaviour - to instantiate an object in a different way. By convention, a classmethod has an additional "cls" argument which acts as a class reference. Take a look at an example below (it is taken from the Sololearn course, as I deem it a good example): 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 = Rectangle.new_square(5) print(square.calculate_area()) The new_square() classmethod allows you to instantiate a Rectangle object in a special way. Normally, you would have to specify two arguments, representing two sides of a rectangle. So normally, you'd create a variable like this: rect = Rectangle(2,4) However, since squares are special kind of rectangles, you can instantiate them by using the classmethod new_square(). How does it work? It Its first argument, cls, represents the class to be called, while side_length - a numeric value. When this method is called it returns the cls - so it calls the regular class __init__ method and since it needs two arguments, it supplies them both being equal to the one you specified as side_length. This way you can easily instantiate an object of a class using a different set of arguments, which might be useful in certain cases. 🇵🇱 Classmethods to są takie "wytrychy", dzięki którym można zmienić np. sposób powoływania obiektów danej klasy. W powyższym przykładzie metoda new_square() odwołuje się do samej klasy i "przekazuje" jej metodzie __init__() oba argumenty, jakich tamta normalnie potrzebuje, ale w inny, niż normalnie, sposób. I to, o dziwo, działa :)
2nd Jul 2017, 8:50 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
Thank you Kuba for your explanation. But if classmethod has "cls" as its argument, shouldn't it call whole class, including classmethod itself? It should work like an endless loop then. Unless "cls" argument applies just to __init__ magic method?
4th Jul 2017, 8:42 PM
Batman1910
Batman1910 - avatar