美文网首页
@property装饰器

@property装饰器

作者: MononokeHime | 来源:发表于2018-07-04 13:28 被阅读0次
  • Python内置的@property装饰器,把一个方法,变成可以像属性那样,做取值用
  • @score.setter,把一个方法,变成可以像属性那样,作赋值用
  • @property和score.setter()同时,表示可读可写
  • 只有@property,表示只读
  • 下面的score()本身是一个方法,本来的用法是s.score()
  • 经过@property,可以像属性那样用s.score,不加括号
class Student(object):

    @property
    def score(self):
        return self._score

    @score.setter
    def score(self, value):
        if not isinstance(value, int):
            raise ValueError('score must be an integer!')
        if value < 0 or value > 100:
            raise ValueError('score must between 0 ~ 100!')
        self._score = value
s = Student()
s.score = 60 # OK,实际转化为s.set_score(60)
s.score # OK,实际转化为s.get_score()

练习:请利用@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):
        self._resolution=self._width*self._height
        return self._resolution

s = Screen()
s.width = 1024
s.height = 768
print('resolution =', s.resolution)
if s.resolution == 786432:
    print('测试通过!')
else:
    print('测试失败!')

相关文章

  • Python进阶——面向对象

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

  • 2018-02-05

    python @property装饰器

  • python中的装饰器

    python中的装饰器 1. @property ['prɑpɚti] @property装饰器就是负责把一个方法...

  • 36-@property装饰器

    @property装饰器 Python内置的@property装饰器可以把类的方法伪装成属性调用的方式 。 将一个...

  • @property

    使用@property装饰器来创建只读属性,@property装饰器会将方法转换为相同名称的只读属性,可以与所定义...

  • @property装饰器

    Python内置的@property装饰器,把一个方法,变成可以像属性那样,做取值用 @score.setter,...

  • property装饰器

    可以利用 字段=property(getfunction,setfuncyion)自定义

  • property 装饰器

    @property 装饰器:把一个方法变成属性调用 例: __str__()返回用户看到的字符串 __repr__...

  • 面向对象进阶

    decorotor - 装饰器/包装器 @property装饰器 之前我们讨论过Python中属性和方法访问权限的...

  • python property装饰器

网友评论

      本文标题:@property装饰器

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