什么时候应该在模型类中使用@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 是一个选项。
当然你可以在函数def coordinates(self)上更改self.coordinates,但是当它被调用为没有()的属性时,这会破坏你代码中的所有地方(也许你的代码是开源的,它不仅会破坏为你)。在这种情况下,@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']