Python:类和子类为什么不在识别子类

2024-09-28 23:20:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个包含salary和bonus属性的类和另一个包含name和idnum属性的类。有一个小程序,询问轮班是否达到了当年的目标,然后计算出当班主管当年的总收入。每次尝试我都会得到:
文件“C:\Python33\12-2.py”,第53行,在main中 班次1=值班主管。员工('28000.0','2240.0','Ian McGregor','S10001') AttributeError:类型对象“Shiftsupervisor”没有属性“Employee” 我做错了什么??在

^{1}$

Tags: 文件namepy程序目标属性main主管
1条回答
网友
1楼 · 发布于 2024-09-28 23:20:08

您的代码存在以下问题:

  1. 我认为最好是ShiftSupervisorEmployee的子类。除非我误会,值长是一种雇员,所以雇员是最基本的阶级。轮班主管可能具有专门化Employee类的附加属性。我添加了shift_number属性来演示这一点。在
  2. 您的main方法只创建员工,但从不处理他们。在
  3. 你的total_income方法有点混乱。记住,__salary和{}是对象的属性。您总是使用instance.attribute的形式来访问它们。在
  4. 在Python中不需要getter和setter。惯例是将它们保留为可公开访问的普通字段,如果确实需要更复杂的访问逻辑,则使用properties。在
  5. 工资和奖金不应该是字符串它们是数值。在

综合起来,您的新代码可能如下所示:

class Employee:
    def __init__(self, salary, bonus, name, idnum):
        self.salary = salary
        self.bonus = bonus
        self.name = name
        self.idnum = idnum

class ShiftSupervisor(Employee):
    def __init__(self, salary, bonus, name, idnum, shift_number):
        super().__init__(salary, bonus, name, idnum)
        self.shift_number = shift_number


def main():
    shift1 = ShiftSupervisor(28000.0, 2240.0, 'Ian McGregor', 'S10001', 1)
    shift2 = ShiftSupervisor(29500, 2360.0, 'Brian Bory', 'S20202', 2)
    shift3 = ShiftSupervisor(28750.0, 2300.0, 'Finn McCool', 'S30045', 3)

    find_income(shift1)
    find_income(shift2)
    find_income(shift3)

def find_income(employee):
    production = input('Did shift {0} make quota this year? Type Y for yes '.format(employee.shift_number))
    if production.lower() == 'y':
        total_income = employee.salary + employee.bonus
    else:
        total_income = employee.salary
    print("{0}'s Total income is: ${1}".format(employee.name, total_income))

main()

我也有种感觉,你在以某种不该发生的方式,把一个轮班和一个员工纠缠在一起,尽管我可以用我的手指去指指点点。一个班次可能有多个员工,而且一个员工可以轮班工作多个班次,但这肯定取决于您要解决的问题。在

相关问题 更多 >