# -*- coding: utf-8 -*-
"""
@File : property.py
@Author : minmin
@Time : 2019\12\10 0010 11:37
"""
"""
@property只读
@property和@*.setter可读可写
@property和@*.setter和@*.deleter可读可写可删除
"""
class Clothes(object):
def __init__(self, style, color, size):
self._style = style
self._color = color
self._size = size
@property
def style(self): # 被@property修饰后,访问该函数时可以当做属性访问
return self._style
@property
def color(self):
return self._color
@property
def size(self):
return self._size
@style.setter
def style(self, style):
self._style = style
@style.deleter
def style(self):
del self._style
def buy(self):
print(self._color + self._style + ' ' + self._size)
if __name__ == '__main__':
clothe = Clothes('卫衣', '黑色', 'XS')
clothe.buy() # 黑色卫衣 XS
clothe.style = '毛衣'
clothe.buy() # 黑色毛衣 XS
del clothe.style
clothe.buy() # AttributeError: 'Clothes' object has no attribute '_style'
# clothe.color = '白色'
# clothe.size = 'XL'
# clothe.buy() # AttributeError: can't set attribute
来源:CSDN
作者:zhaijunmin2
链接:https://blog.csdn.net/zhaijunmin2/article/details/103478925