What's the difference between a class property and a class method? As I understand it, property is calculated when an object is created. And method makes calculations when I call it.
Is there any other difference than that?
For example, I have a property
in my class Product()
:
@property
def total_ammount_in_store(self):
consignments = self.product.package.consignments
total_ammount = 0
for consignment in consignments:
total_ammount += consignment.package_ammount
When I render some page, I pass some products. For example:
{'products':Product.objects.filter(expiration_data < datetime.now())
I don't need to calculate total_ammount_in_store
every time I get an instance of Product
. What if I just need to calculate it when I call it in a template: {{product.total_ammount_in_store}}? Is it possible?
Is method also calculated when the object is created?
In most cases, methods are actions and properties are qualities. Using a method causes something to happen to an object, while using a property returns information about the object or causes a quality about the object to change.
The main difference between Class and Method is that class is a blueprint or a template to create objects while method is a function that describes the behavior of an object. A programming paradigm is a style that explains the way of organizing the elements of a program.
A class method is a method which is bound to the class and not the object of the class. They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance. It can modify a class state that would apply across all the instances of the class.
Instance methods need a class instance and can access the instance through self . Class methods don't need a class instance. They can't access the instance ( self ) but they have access to the class itself via cls .
The property is called each time you access product.total_ammount_in_store
, not at the time when the product is created.
Therefore including {{ product.total_ammount_in_store }}
in your template will do the right thing.
By using the property decorator, you can access product.total_ammount_in_store
instead of product.total_ammount_in_store()
if it was an instance method. In the Django template language, this difference is not so apparent, because Django will call the method automatically in the template.
Don't confuse an instance method with a class method, which is quite different. A class method belongs to your class Product
, not an individual instance product
. You don't have access to instance variables e.g. self.package
when you call a class method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With