Python装饰器的使用

  • Post author:
  • Post category:python


class Employee:
    #属性私有化
    def __init__(self,name,salary):
        self.__name = name
        self.__salary = salary

    @property
    def salary(self):
        return self.__salary
    @salary.setter
    def salary(self,salary):
        if (5000 < salary < 50000):
            self.__salary = salary
        else:
            print("设置错误薪资的范围是5000-5W")

#装饰器直接调用,比较方便
emp1 =Employee("李四",30000)
print(emp1.salary)
emp1.salary = -2000
print(emp1.salary)

# 和上面实现内容一致,实现不一致,上面使用装饰器
class Employee2: 
#属性私有化 
    def __init__(self,name,salary): 
        self.__name = name 
        self.__salary = salary 
#这个是普通的类内函数定义
    def get_salary(self):
        return self.__salary
    def set_salary(self,salary):
        if(5000<salary<50000):
            self.__salary=salary
        else:
            print("设置错误薪资的范围是5000-5W")

emp2 = Employee2("杭三",50000)
print(emp2.get_salary())
emp2.set_salary(60000)



版权声明:本文为weixin_63145323原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。