ali*_*s51 1 django django-models
在阅读文档时,很少有关于如何以及为何在类中使用 @property 的信息。我能找到的只有:
\n\n\n\n\n也称为 \xe2\x80\x9c 托管属性\xe2\x80\x9d,是 Python 自 2.2 版以来的一项功能。这是实现属性的一种巧妙方法,其用法类似于属性访问,但其实现使用方法调用。
\n
当我在模型中有一个函数时,def get_absolute_url(self):我应该用 来装饰它@property吗?
@property\ndef get_absolute_url(self):\n pass\nRun Code Online (Sandbox Code Playgroud)\n\ndef未装饰的和装饰过的有什么区别@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']
Run Code Online (Sandbox Code Playgroud)
正如你所看到的revers_coordinates(),有反应,也self.coordinates没有反应。如果你想让它做出反应,@property这是一个选择。
当然,您可以只更改self.coordinatesfunction def coordinates(self),但是当它作为属性调用时,这会破坏代码中的所有位置()(也许您的代码是开源的,它不仅会破坏您)。在这种情况下@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']
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3026 次 |
| 最近记录: |