下面用一个例子来理解python中@property的用法
class DataSet(object):
def __init__(self):
self._images = 255
self._labels = "positive"
@property
def images(self): # 方法加入@property后,这个方法相当于一个属性,这个属性可以让用户进行使用,而且用户有没办法随意修改。
return self._images
def labels(self):
return self._labels
ds = DataSet()
# level one
ds._images = 1 # 用户可以随意修改属性,这样的代码不好
# level two
print(ds.labels()) # 用方法来返回属性,这样用户不能随意修改,但是需要加(),看上去就不像个属性了
# level three
print(ds.images) # 加了@property的好处是可以不加(),直接像访问属性一样访问类方法,这样看上去就像个属性了,同时把_images属性保护起来了
相关资料
[1] python @property的介绍与使用
[2] Python @property decorator



