python property decorator [duplicate]

孤者浪人 提交于 2019-12-20 11:36:17

问题


Possible Duplicate:
Real world example about how to use property feature in python?

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]

回答1:


It's simply syntactic sugar. It allows a method call to look like a variable access or assignment.

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.



来源:https://stackoverflow.com/questions/11513705/python-property-decorator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!