美文网首页
python个人学习——@property

python个人学习——@property

作者: 布织岛 | 来源:发表于2020-05-16 15:20 被阅读0次

类里面,@property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程序运行时就减少了出错的可能性。

@property  #getting

@xxx.setter   #setting

关于只读属性:只定义getter方法,不定义setter方法就是一个只读属性。

关于,函数命名,和变量:

1 getting和setting函数的函数名相同

2 self._width 或者self.__width,一定要有下划线(不确定,以后再确定。但无下划线会报错

例子:

请利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution:

代码:

class Screen(object):

    @property

    def width(self):

        return self._width

    @width.setter

    def width(self,value):

        self._width=value

    @property

    def height(self):

        return self._height

    @height.setter

    def height(self,value):

        self._height=value

    @property

    def resolution(self):

        return self._width * self._height

#测试

s = Screen()

s.width = 1024

s.height = 768

print('resolution =', s.resolution)

if s.resolution == 786432:

    print('测试通过!')

else:

    print('测试失败!')

相关文章

  • python个人学习——@property

    类里面,@property广泛应用在类的定义中,可以让调用者写出简短的代码,同时保证对参数进行必要的检查,这样,程...

  • python学习-@property

    视频讲解:读源码需要的python技能: decorator property:https://www.bilib...

  • Python进阶——面向对象

    1. Python中的@property   @property是python自带的装饰器,装饰器(decorat...

  • 2018-02-05

    python @property装饰器

  • python @property

    参考 Python进阶之“属性(property)”详解 - Python - 伯乐在线

  • Python中property中的小坑

    刚刚了解了python中的@property的使用,property本质是python中的一个内置修饰器。使用大概...

  • property, getter, setter and del

    http://www.runoob.com/python/python-func-property.htmlhtt...

  • Python property

    Question 我们一般对属性的的操作主要有2个,访问和修改。看个例子。 我们叫这种使用属性的方式叫点模式(我自...

  • python @property

    1.描述符 我们首先要搞懂描述符(Descriptor)是什么. 1.1 描述符定义 只要类中有__get__()...

  • Python @property

    以下内容来自万能的互联网... 首先教材上的@property 可以将一个方法的调用变成“属性调用”,主要用于帮助...

网友评论

      本文标题:python个人学习——@property

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