【问题标题】:Can we apply getter and setter for Employees to automatically raise in pay(where we defined applyraise) when we increase the raiseamount [closed]当我们增加 raiseamount 时,我们可以为员工应用 getter 和 setter 以自动提高工资(我们定义 applyraise)[关闭]
【发布时间】:2020-07-18 10:01:28
【问题描述】:
#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)

【问题讨论】:

  • 欢迎来到 SO,您能否添加一些上下文、预期的输入和输出。
  • 也许你可以在构造函数上设置它,方法是向 raiseamount def __init__(self, first, last, pay, raseamount = 1.05) 添加一个默认值:
  • 如果你加注emp1.raiseamount,那么self.pay将自动增加,因为它是在emp1.raiseamount的基础上计算的。如果这不是您需要的,请更好地解释一下
  • 如果您可以在程序中添加代码,@badhushamuhammed 将不胜感激。谢谢。
  • 是的,好吧,然后去设置器或在applyraise(self, raiseamount=1.05):函数中使用它。

标签: python class pycharm getter-setter


【解决方案1】:

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

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金额改变了,apply raise也完成了。

【讨论】:

  • 非常感谢,大卫。属性装饰器和设置器的想法完美地工作。现在不必手动发出命令来在 applyraise 中添加 raiseamount。它会自动添加。只是一个查询 - 为什么你在 raiseamount 之前使用了 __double 下划线?再次感谢!
  • 那么它就像私有的,在内部更改名称以便没有来自类外部的直接访问
猜你喜欢
  • 2014-02-18
  • 1970-01-01
  • 2012-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多