属性和类方法有什么区别?

And*_*rew 7 python django django-models

property和class有method什么区别?据我了解,属性是在创建对象时计算的。方法在我调用时进行计算?还是有其他区别?例如,我有一个property在我的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
Run Code Online (Sandbox Code Playgroud)

渲染某些页面时,例如传递一些产品给{'products':Product.objects.filter(expiration_data < datetime.now()) 我:例如,我不需要total_ammount_in_store每次获取的实例时都进行计算Product。如果我在模板{{product.total_ammount_in_store}}中调用它时只需要计算该怎么办?可能吗?甚至方法都可以计算对象的创建位置?

Ala*_*air 9

每次访问时都会调用该属性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当您调用类方法时,您无权访问实例变量。