前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python:@property装饰器的使用

Python:@property装饰器的使用

作者头像
用户7886150
修改2021-01-22 10:45:40
5860
修改2021-01-22 10:45:40
举报
文章被收录于专栏:bit哲学院

参考链接: Python @property装饰器

@property:(把方法变成属性调用) 

Python内置的@property装饰器就是负责把一个方法变成属性调用的 Python允许我们在程序中手动设置异常,使用 raise 语句即可 把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作 

# 例1:学生分数设置和获取

class Student(object):

    @property

    def score(self):

        return self._score

    @score.setter

    def score(self, value):

        if not isinstance(value, int):

            raise TypeError('score must be an integer')

        if value > 100 or value < 0:

            raise ValueError('score must be between 0 and 100')

        self._score = value

s1 = Student()

s1.score = 100  # 实际就是set_score

print(s1.score)  # 实际就是get_score

还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性 

# 例2:学生生日的设置和获取

class Student(object):

    @property

    def birthday(self):

        return self._birthday

    @birthday.setter

    def birthday(self, value):

        self._birthday = value

    def age(self):

        return 2020 - self._birthday

s1 = Student()

s1.birthday = 1998

print(s1.birthday)

print(s1.age())

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

# 例3:计算长方形的面积

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('测试失败!')

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档