我们可以申请 getter 和 setter 让员工在我们增加 raiseamount 时自动加薪(我们定义 applyraise 的地方)

Can we apply getter and setter for Employees to automatically raise in pay(where we defined applyraise) when we increase the raiseamount

#here is the code

class Employee:

    noofemps = 0
    raiseamount = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first + '.' + last + '@email.com'

        Employee.noofemps += 1

    def fullname(self):
        return '{} {}'.format(self.first.title(), self.last.title())

    def applyraise(self):
        self.pay = int(self.pay * self.raiseamount)

emp1 = Employee('rahul', 'sharma', 30000)
emp2 = Employee('dev', 'verma', 40000)

你可能会喜欢这个。我删除了简短的电子邮件。

class Employee:

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay
        self.__raiseamount = 1.05

    def applyraise(self):
        self.pay = int(self.pay * self.raiseamount)

    @property
    def raiseamount(self):
        return self.__raiseamount

    @raiseamount.setter
    def raiseamount(self, new_raise_amount):
        self.__raiseamount = new_raise_amount
        self.applyraise()

emp2 = Employee('dev', 'verma', 40000)
emp2.applyraise()
print(emp2.pay, emp2.raiseamount)
emp2.raiseamount = 1.1
print(emp2.pay, emp2.raiseamount)

然后就这样出来了

42000 1.05
46200 1.1

这样你会看到,当你设置raiseamount时,不仅raise amount改变了,apply raise也完成了。