【Python入门】使用@property

使用@property

有没有既能够检查参数,又可以用类似属性这样简单的方式来访问类的变量呢?

有!

对于类的方法,装饰器一样起作用!Python内置的@property装饰器就是负责把一个方法变成属性调用的:

还记得装饰器(decorator)可以给函数动态加上功能吗?对于类的方法,装饰器一样起作用。Python内置的@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 between 0 ~ 100!')
        self._score = value

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

class Student(object):

    @property
    def birth(self):
        return self._birth

    @birth.setter
    def birth(self, value):
        self._birth = value

    @property
    def age(self):
        return 2015 - self._birth

上面的birth是可读写属性,而age就是一个只读属性,因为age可以根据birth和当前时间计算出来。

特别注意的一点:在类中调用属性时,应当使用self._birth的格式,而不是self.birth

猜你喜欢

转载自blog.csdn.net/Zeke_Leeeee/article/details/87886552
今日推荐