首页 > 解决方案 > 什么时候应该在模型类中使用@property?

问题描述

在阅读文档时,几乎没有关于如何以及为什么在课堂上使用 @property 的信息。我能找到的只有:

也称为“托管属性”,是 Python 2.2 版以来的一项功能。这是实现属性的一种巧妙方法,其用法类似于属性访问,但其实现使用方法调用。

当我在模型中有一个函数时,我def get_absolute_url(self):应该用它来装饰它@property吗?

@property
def get_absolute_url(self):
    pass

def没有装饰的和有装饰的有什么区别@property?我什么时候应该使用它,什么时候不应该使用它?

标签: djangodjango-models

解决方案


什么时候应该在模型类中使用@property?

@property当您的类属性由类中的其他属性形成时,您应该使用它,并且您希望它在源属性更改时得到更新。

没有@property 的示例

class Coordinates():
    def __init__(self, x, y):
        self.x = 'x'
        self.y = 'y'
        self.coordinates = [self.x, self.y]

    def revers_coordinates(self):
        return [self.y, self.x]

>>> a = Coordinates('x', 'y')
>>> a.coordinates
['x', 'y']
>>> a.revers_coordinates()
['y', 'x']
>>> a.x = 'z'
>>> a.coordinates 
['x', 'y'] # <===== no changes in a.x
>>> a.revers_coordinates()
['y', 'z']

正如你看到revers_coordinates()的反应,并self.coordinates没有。如果您希望它做出反应,这@property是一种选择。

当然,您可以只更改self.coordinatesfunction def coordinates(self),但这会破坏代码中的所有位置,当它被称为没有属性时()(也许您的代码是开源的,它不仅会破坏您)。在这种情况下,@property 就是您想要的。

@property 示例

class CoordinatesP():
    def __init__(self, x, y):
        self.x = 'x'
        self.y = 'y'
    
    @property
    def coordinates(self):
        return [self.x, self.y]

    def revers_coordinates(self):
        return [self.y, self.x]

>>> a = CoordinatesP('x', 'y')
>>> a.coordinates
['x', 'y']
>>> a.revers_coordinates()
['y', 'x']
>>> a.x = 'z'
>>> a.coordinates
['z', 'y'] # <===== a.x has changed
>>> a.revers_coordinates()
['y', 'z']

推荐阅读