尝试将类/函数的总小时数调用到我在下面创建的类的实例。 (希望我措辞正确)
class Employee:
def __init__(self):
self.wage = 0
self.hours = 0
if self.hours > 40:
self.ot = self.hours - 40 #overtime hours
self.earned_ot = self.wage * 1.5 #overtime wage rate
self.ot_total = self.ot * self.earned_ot #pay for overtime hours
self.pay = self.wage * 40 #standard hour wage
self.total = self.pay + self.ot_total #standard wage + ot hour wage
else:
self.total = self.wage * self.hours
alice = Employee()
alice.wage = 20
alice.hours = 40
#alice.total =
bob = Employee()
bob.wage = 15
bob.hours = 50
#bob.total =
print("Alice: \n Net pay: ${} \nBob: \n Net pay: ${}" .format(alice.total,
bob.total))
问题我似乎已经足够简单,但我无法解决这个问题。我现在已经注释掉了alice.total和bob.total,但这些是我需要的才能使打印正常工作。
我觉得我忘了简单的事情,但浏览我的笔记/文字我无法弄清楚。是否有人看到我遇到过的问题,是否有可能解释这个问题的链接?我没有找到一个彻头彻尾的答案,只是朝着正确的方向前进。
感谢。
答案 0 :(得分:2)
我认为您正在寻找的是the @property decorator:
class Employee:
def __init__(self):
self.wage = 0
self.hours = 0
@property
def total(self):
if self.hours > 40:
ot = self.hours - 40 #overtime hours
earned_ot = self.wage * 1.5 #overtime wage rate
ot_total = ot * earned_ot #pay for overtime hours
pay = self.wage * 40 #standard hour wage
return pay + ot_total #standard wage + ot hour wage
else:
return self.wage * self.hours
答案 1 :(得分:0)
看起来您的代码会从将构造函数更改为:
中受益class Employee:
def __init__(self, wage=0, hours=0):
self.wage = wage
self.hours = hours
并将其余代码放在方法中:
class Employee:
....
def get_total(self):
total = ... # calculate from self.wage and self.hours
return total
alice = Employee(wage=20, hours=40)
print(alice.get_total())
答案 2 :(得分:0)
您可以更改构造函数
class Employee:
def init(self, wage=0, hours=0):
self.wage = wage
self.hours = hours
并实例化您的员工
alice = Employee(20, 40)
其余代码可以保持不变。
但是我会建议使用类似属性的东西,这样你就可以在不创建新Employee
的情况下更改工资/小时数,并且仍能获得准确的值
class Employee:
def init(self):
self._wage = 0
self._hours = 0
@property
def wage(self):
return self._wage
@wage.setter
def wage(self, value):
self._wage = value
@property
def hours(self):
return self._hours
@hours.setter
def hours(self, value):
self._hours = value
@property
def total(self):
if self.hours > 40:
self.ot = self.hours - 40 #overtime hours
self.earned_ot = self.wage * 1.5 #overtime wage rate
self.ot_total = self.ot * self.earned_ot #pay for overtime hours
self.pay = self.wage * 40 #standard hour wage
return self.pay + self.ot_total #standard wage + ot hour wage
else:
return self.wage * self.hours
您在Employee
实例化和获取/设置工资/小时的代码可以保持不变
有关财产的更多详情:https://www.programiz.com/python-programming/property
编辑:根据所做的评论修改我的答案