美文网首页
Python属性的get和set方法

Python属性的get和set方法

作者: 继即鲫迹极寂寂 | 来源:发表于2019-01-17 15:41 被阅读0次

    类的属性通常可以在init方法里定义:

    class Animal(object):
        def __init__(self, height):
            self.height = height
    

    但是这样定义不能校验传入的参数,所以通常要把参数设置为私有变量,在变量名前加下划线:

    class Animal(object):
        def __init__(self, height):
            self._height = height
    

    然而这样属性在外部就不可读写,这时需要增加get、set方法:

    class Animal(object):
        def get_height(self):
            return self._height
    
        def set_height(self, value):
            if not isinstance(value, float):
                raise ValueError("高度应该是小数")
            if value < 0 or value > 300:
                raise ValueError("高度范围是0到300cm")
            self._height = value
    d = Animal()
    d.set_height(250.9)
    print(d.get_height()) --------------> 250.9
    

    但是这样在外部调用时代码很繁琐,在这里用装饰器@property简化get、set方法

    class Animal(object):
        @property
        def height(self):
            return self._height
        @height.setter
        def height(self, value):
            if not isinstance(value, float):
                raise ValueError("高度应该是小数")
            if value < 0 or value > 300:
                raise ValueError("高度范围是0到300cm")
            self._height = value
    
    d = Animal()
    d.height = 250.9
    print(d.height) --------------> 250.9
    

    相关文章

      网友评论

          本文标题:Python属性的get和set方法

          本文链接:https://www.haomeiwen.com/subject/ypeidqtx.html