Python 装饰器之 Property: Setter 和 Getter

2021/8/27 20:37:04

本文主要是介绍Python 装饰器之 Property: Setter 和 Getter,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、什么是setter,getter

@property的实现比较复杂,我们先考察如何使用。

把一个getter方法变成属性,只需要加上@property就可以了,此时,@property本身又创建了另一个装饰器@score.setter,负责把一个setter方法变成属性赋值,于是,我们就拥有一个可控的属性操作.

refer to:https://www.geeksforgeeks.org/getter-and-setter-in-python/

二、使用场景

Case1:对属性的赋值做判断和异常检测

class Geeks:
    def __init__(self):
        self._age = 0

    # using property decorator
    # a getter function
    @property
    def age(self):
        print("getter method called")
        return self._age

    # a setter function
    @age.setter
    def age(self, a):
        if a < 18:
            raise ValueError("Sorry you age is below eligibility criteria")
        print("setter method called")
        self._age = a # setting the age using setter


if __name__ == '__main__':
    g = Geeks()
    age_before_set = g.age
    print(age_before_set)  # 0
    g.age = 19
    age_after_set = g.age
    print(age_after_set)  # 19

 

Case2:将 setter 和 getter 作为私有方法隐藏起来

class FinalClass:

    def __init__(self, var):
        ## calling the set_a() method to set the value 'a' by checking certain conditions
        self.__set_a(var)

    ## getter method to get the properties using an object
    def __get_a(self):
        return self.__a

    ## setter method to change the value 'a' using an object
    def __set_a(self, var):

        ## condition to check whether var is suitable or not
        if var > 0 and var % 2 == 0:
            self.__a = var
        else:
            self.__a = 2

    a = property(__get_a, __set_a)

Case3:多种属性之间的动态依赖关系

refer to:https://iphysresearch.github.io/blog/post/programing/python/property_setter/

 



这篇关于Python 装饰器之 Property: Setter 和 Getter的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程