+6

Does somebody knows how to use @classmethod ?

I want to use one class's variable in another class, how to perform it?

12/3/2019 4:35:09 PM

WhyFry

8 Answers

New Answer

-1

Here what I did: class Item(models.Model): quantity = models.IntegerField(default=1) def minus_order(self): self.quantity-=Order.qtt class Order(models.Model): qtt = models.IntegerField(default=1) @classmethod def order_qtt(cls): return cls.qtt

+7

Here is a link to a document in SL: https://www.sololearn.com/learn/Python/2473/

+4

@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>

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

+2

I want to subtract order quantity from item quantity each time item was ordered. in django - project - app products - models.py: this is oversimplified version: class Item(models.Model): quantity = models.IntegerField(default=1) class Order(models.Model): qtt = models.IntegerField(default=1)

+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