python_property属性

添加property属性

class Color:
    def __init__(self, rgb_value, name):
        self.rgb_value = rgb_value
        self._name = name
    
    def _set_name(self, name):
        print("set name")
        if not name:
            raise Exception("Invalid Name")
        self._name = name
    
    def _get_name(self):
        print("get name")
        return self._name
        
    pro = property(_get_name, _set_name)

代码调试

>>> c=Color("1","red")
>>> c.pro
get name
'red'
>>> c.pro="blue"
set name  

#使用装饰器创建property

class Color:
    def __init__(self, rgb_value, name):
        self.rgb_value = rgb_value
        self._name = name
    
    @property
    def color(self):
        print("get name")
        return self._name
    
    @color.setter
    def color(self, name):
        print("set name")
        if not name:
            raise Exception("Invalid Name")
        self._name = name

你可能感兴趣的:(python)