Python наследство. Переменная поля не существует? - PullRequest
0 голосов
/ 05 мая 2020

У меня есть класс служащих, который является суперклассом класса производственных рабочих. Возникает проблема, при которой экземпляр производственного работника, похоже, не распознает существование одного из определенных полей своего суперкласса (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("-------------------")

1 Ответ

1 голос
/ 05 мая 2020

Вы назначили свой класс в setEmpNum, но не извлекаете переменную класса при вызове getEmpNum.

Вы хотите, чтобы ваш получатель также ссылался на атрибут класса:

def getEmpNum(self):
    return self.__empNum
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...