首页 > 解决方案 > Python 继承。字段变量不存在?

问题描述

我有一个员工类,它是生产工人类的超类。存在一个问题,生产工人的实例似乎无法识别其超类 (Employee) 的已定义字段之一的存在

这是错误消息以及我在程序中输入的内容

Please enter the employee's number: 9987
Please enter the employee's name: Leo
Please enter the employee's shift number (1 for day shift 2 for night shift): 2
Please enter the employee's hourly pay rate: 18.67
-------------------
Here is some information about your employee
Traceback (most recent call last):
  File "jdoodle.py", line 46, in <module>
    main()
  File "jdoodle.py", line 40, in main
    print("Here is their employee number: " + str(person.getEmpNum()))
  File "jdoodle.py", line 12, in getEmpNum
    return __empNum
NameError: name '_Employee__empNum' is not defined

这是类定义

class Employee:
    def setName(self, name):
        self.__empName = name

    def setEmpNum(self, empNum):
        self.__empNum = empNum

    def getName(self):
        return __empName

    def getEmpNum(self):
        return __empNum
class ProductionWorker(Employee):
    def setShiftNum(self, num):
        self.__shiftNum = num

    def setPayRate(self, payrate):
        self.__payrate = payrate

    def getShiftNum(self):
        return __shiftNum

    def getPayRate(self):
        return __payrate

这里是主要方法

def main():   
    person = ProductionWorker()
    empNum = int(input("Please enter the employee's number: "))
    empName = input("Please enter the employee's name: ")
    shiftNum = int(input("Please enter the employee's shift number (1 for day shift 2 for night shift): "))
    payrate = float(input("Please enter the employee's hourly pay rate: "))
    person.setName(empName)
    person.setEmpNum(empNum)
    person.setShiftNum(shiftNum)
    person.setPayRate(payrate)

    print("-------------------")
    print("Here is some information about your employee")
    print("Here is their employee number: " + str(person.getEmpNum()))
    print("Here is their name: " + person.getName())
    print("Here is their payrate: " + str(person.getPayRate()))
    print("Here is their shift number: " + str(person.getShiftNum()))
    print("-------------------")

标签: pythonclassinheritance

解决方案


您已分配给您的班级,setEmpNum但没有在调用getEmpNum.

您将希望您的 getter 也引用 class 属性:

def getEmpNum(self):
    return self.__empNum

推荐阅读