[英]what's the difference between property and class method?
類屬性和類方法有什么區別? 據我了解,屬性是在創建對象時計算的。 當我調用它時,方法會進行計算。
除此之外還有什么區別嗎?
例如,我的class Product()
有一個property
:
@property
def total_ammount_in_store(self):
consignments = self.product.package.consignments
total_ammount = 0
for consignment in consignments:
total_ammount += consignment.package_ammount
當我呈現一些頁面時,我傳遞了一些產品。 例如: {'products':Product.objects.filter(expiration_data < datetime.now())
我不需要每次獲得Product
實例時都計算total_ammount_in_store
。 如果我只需要在模板中調用它時計算它呢:{{product.total_ammount_in_store}}? 是否可以?
創建對象時是否也計算方法?
每次訪問product.total_ammount_in_store
時都會調用該屬性,而不是在創建產品時調用。
因此,在您的模板中包含{{ product.total_ammount_in_store }}
會做正確的事情。
通過使用屬性裝飾器,您可以訪問product.total_ammount_in_store
而不是product.total_ammount_in_store()
如果它是一個實例方法。 在 Django 模板語言中,這種區別並不那么明顯,因為 Django 會自動調用模板中的方法。
不要將實例方法與類方法混淆,這是完全不同的。 類方法屬於您的Product
類,而不是單個實例product
。 當您調用類方法時,您無權訪問實例變量,例如self.package
。
@property
裝飾器可用於為您的類的實例變量實現一個 getter(在您的情況下它將是self.total_ammount_in_store
)。 每次調用some_product.total_ammount_in_store
,都會執行裝飾方法。 僅在創建新對象時執行它是沒有意義的 - 您想在商店中獲取當前數量,不是嗎? 更多關於@property
閱讀在 Python 文檔中(它是 Python 的構造,而不是 Django 的):
https://docs.python.org/2/library/functions.html#property
至於類方法,它們是完全不同的東西。 顧名思義,它們綁定到類,而不是實例。 因此,調用類方法不需要實例,但也不能在類方法中使用任何實例變量(因為它們綁定到特定實例)。
對於您問題中與 Django 相關的部分...
如果您在模板中包含{{ some_product.total_ammount_in_store }}
,那么每次顯示頁面時,都會從some_product
實例中獲取 store 中的總金額。 這意味着調用了裝飾的total_ammount_in_store
getter。
例如,如果商店的總金額在產品生命周期內沒有改變,您可以在__init__
方法中計算金額,然后只返回該值。 如果總金額可以更改,您也可以這樣做,但您需要確保每次更改金額時都重新計算金額 - 例如通過調用方法。 像這樣:
class Product(object):
def __init__(self):
# ...
# other initialization
# ...
self.recalculate_amount()
def recalculate_amount(self):
consignments = self.product.package.consignments
self._total_amount = 0
for consignment in consignments:
self._total_amount += consignment.package_amount
@property
def total_amount(self):
"""Get the current total amount in store."""
return self._total_amount
然后每次您調用some_product.total_ammount_in_store
時仍然會調用some_product.total_ammount_in_store
(例如在您的 Django 模板中),但它不會每次都計算數量 - 它會使用存儲的數量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.