@property装饰器

落花浮王杯 提交于 2019-12-10 17:47:41
# -*- 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


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