Python3-2020-测试开发-20- Python中装饰器@property

hongxiangping 2020-06-09

装饰器

为私有属性提供getter和setter方法

原始实现代码:

class Employee01:

    def __init__(self,name,age):

        self.__name = name
        self.__age = age


    def get_age(self):

        return self.__age

    def set_age(self,age):

        if 1 < age <200:

            self.__age = age
        else:

            print("年龄不符合规则")

    @property
    def salary(self):

        print("salary run ...")

        return 10


e = Employee01("chu01",18)
# e.salary()

print(e.salary)

"""
salary run ...
10
"""


e.set_age(100)
print(e.get_age())    # 100

使用装饰器优化代码

class Employee02:

    def __init__(self,name,age):

        self.__name = name
        self.__age = age

    @property
    def age(self):

        return self.__age

    @age.setter
    def age(self,age):

        if 1 < age <=200:

            self.__age = age
        else:

            print("年龄不符合规则")



e2 = Employee02("chu02",200)
# e2.age = -200                   # 年龄不符合规则

e2.age = 200
print(e2.age)    # 200

相关推荐