python属性装饰器 [英] python property decorator
问题描述
我对以下代码中看到的装饰器 @property
有疑问。有人会足够仁慈地完全解释为什么有人会使用 @property
装饰器吗?我知道 @property
等效于 isActive = property(isActive)
,但是method属性实际上对它的参数做了什么?如果我要从 InputCell
类调用 isActive
方法,实际上会发生什么?
I have a question about the decorator @property
that I've seen in the following code. Could someone be kind enough to completely explain why someone would use the @property
decorator? I know @property
is equivalent to isActive = property(isActive)
but what does the method property actually do to it's parameter? If I were to call the isActive
method from the InputCell
class what would actually happen? Thanks in advance.
class InputCell(object):
def __init__(self, ix, iy, inputData):
self.ix = ix
self.iy = iy
self.InputData = inputData
@property
def isActive(self):
return self.InputData[self.ix][self.iy]
推荐答案
这只是语法糖。
一种有用的方法是,如果您想更改以前是的内容, em>一个简单的变量,用于使用其他代码实际计算或验证的内容。如果将其设置为属性,则可以在不破坏任何现有代码的情况下执行此操作。另一种方法是用于对象属性的缓存,延迟初始化等。
One way this can be useful is if you want to change something that previously was a simple variable to something that's actually computed or validated with other code. If you make it a property, you can do this without breaking any existing code. Another way is for caching, lazy initialization, etc., of object attributes.
这篇关于python属性装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!