django - 什么时候应该在模型类中使用@property?
问题描述
在阅读文档时,几乎没有关于如何以及为什么在课堂上使用 @property 的信息。我能找到的只有:
也称为“托管属性”,是 Python 2.2 版以来的一项功能。这是实现属性的一种巧妙方法,其用法类似于属性访问,但其实现使用方法调用。
当我在模型中有一个函数时,我def get_absolute_url(self):
应该用它来装饰它@property
吗?
@property
def get_absolute_url(self):
pass
def
没有装饰的和有装饰的有什么区别@property
?我什么时候应该使用它,什么时候不应该使用它?
解决方案
什么时候应该在模型类中使用@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.coordinates
function 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']
推荐阅读
- python - 在 pycharm IDE 中,我正在处理 face_recognition,PIL 模块,但在代码下方运行时,它不显示图像
- azure - 通过自定义角色密钥库的 ARM 模板进行蓝图部署
- layout - SwiftUI 中的 Selfsize 网格项
- c# - C# 复制
来自其他班级 - paypal - 从我的客户电子邮件地址获取 PayPal 客户 ID
- c# - FileNotFoundException WpfAnimatedGif
- flutter - Flutter中Expandable中flex的默认值是多少?
- react-native - 如何在 ReactNative 中将多个 FlatList 项目发送到另一个屏幕?
- netsuite - 无法在 .each() 方法中更新 Netsuite 中的子列表字段
- reporting-services - 如何在 SSRS 报表生成器模板上的值之后显示文本?