New course! Every coder should learn Generative AI!
Try a free lesson+ 8
@classmethod is similar to @staticmethod but with more features . Useing @classmethod u can call method of class without creating object.u can use it when u don't want create a object of a class .
pass class name to another class as a argument then u can use its variable it's done thies way check out the code .
code from udemy
class FixedFloat:
def __init__(self, amount):
self.amount = amount
def __repr__(self):
return f'<FixedFloat {self.amount:.2f}>'
@classmethod
def from_sum(cls, value1, value2):
return cls(value1 + value2)
class Euro(FixedFloat):
def __init__(self, amount):
super().__init__(amount)
self.symbol = '€'
def __repr__(self):
return f'<Euro {self.symbol}{self.amount:.2f}>'
"""
When we now call:
* `Euro.from_sum()`, `cls` is the `Euro` class.
* `FixedFloat.from_sum()`, `cls` is the `FixedFloat` class.
"""
print(Euro.from_sum(16.7565, 90)) # <Euro €106.75>
+ 7
Here is a link to a document in SL: https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2473/
+ 4
Quickly and in short the difference between regular methods, class and static in Python:
Regularly methods automatically pass the instance as first argument so that you can access it from the body.
def m(self):
...
Classmethods automatically pass the CLASS as first argument.
def m(cls):
...
And static methods don't pass anything at all, unless you say so.
+ 2
Can you describe a bit more what you plan to do? There could be several solutions.
+ 1
Classmethod is called by the class, which is passed to the cls parameter, then an instance of the class is created that uses other parameters.
- 1
Google bro