python - 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("-------------------")
解决方案
您已分配给您的班级,setEmpNum
但没有在调用getEmpNum
.
您将希望您的 getter 也引用 class 属性:
def getEmpNum(self):
return self.__empNum
推荐阅读
- mongodb - Windows 机器上的 MongoDB 复制
- javascript - (ES6)使用输入字段过滤数据(min.array)
- python-3.x - 数组行的成对减法和for循环中的除法
- javascript - 按钮单击不会提醒 div 内容
- android - 如何检查 TextToSpeech 是否使用指定的语音引擎初始化?
- presto - 尝试启动 Presto 时的回溯
- node.js - 要求('fs')不适用于角度和电子
- php - 英国邮政编码 - 按距离排序
- node.js - async.parallel 如何在单线程的 nodejs 中工作
- objective-c - 使用 kinfo_proc 时出现 EXC_BAD_ACCESS 错误