Python基础学习(使用@property)

Python基础学习(使用@property)

我们可以通过设置私有变量将类中的属性隐藏起来,然后通过方法对其进行修改和参数检查。但这样做有时会显得比较冗余,可以使用@property将方法变为属性来进行调用。

例如:

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 be 0 ~ 100!')
        self.__score = value
student_A = Student()
student_A.score = 50
print(student_A.score)
50
student_A.score = 10000
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-8-8c771a8ad78f> in <module>
----> 1 student_A.score = 10000


<ipython-input-5-e77234502a3f> in score(self, value)
     10             raise ValueError('score must be an integer')
     11         if value < 0 or value > 100:
---> 12             raise ValueError('score must be 0 ~ 100!')
     13         self.__score = value


ValueError: score must be 0 ~ 100!

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

class Screen(object):
    
    @property
    def width(self):
        return self.__width
    
    @width.setter
    def width(self, value):
        if not isinstance(value, int):
            print('Please input a integer!')
        if value < 0:
            print('Please input a positive number')
        self.__width = value
    
    @property
    def height(self):
        return self.__height
    
    @height.setter
    def height(self, value):
        if not isinstance(value, int):
            print('Please input a integer!')
        if value < 0:
            print('Please input a positive number')
        self.__height = value
    
    #设置只读属性,即不写它的设置方法
    @property
    def resolution(self):
        return self.__width * self.__height
screen_A = Screen()
screen_A.width = 10
print(screen_A.width)
10
screen_A.height = 50
print(screen_A.height)
50
print(screen_A.resolution)
500
screen_A.resolution = 100
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-14-c15e19203741> in <module>
----> 1 screen_A.resolution = 100


AttributeError: can't set attribute
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值