我对此计划的目标是记录4条信息(员工编号,员工姓名,班次编号和每小时工资率),然后显示它们。我需要在这个程序中使用类。
这是类代码:
class Employee(object):
def __init__(self, name, number):
self.__name = name
self.__number - number
def set_name(self, name):
self.__name = name
def set_number(self, number):
self.__number = number
def get_name(self):
return self.__name
def get_number(self):
return self.__number
class ProductionWorker(Employee):
def __init__(self, name, number,
shift, payRate):
Employee.__init__(self, name, number)
self.__shift = shift
self.__payRate = payRate
def set_shift(self, shift):
self.__shift = shift
def set_payRate(self, payRate):
self.__payRate = payRate
def get_shift(self):
return self.__shift
def get_payRate(self):
return self.__payRate
以下是导入类代码并执行它的代码:
import employee
name = input('Name: ')
number = input('Employee Number: ')
shift = input('Shift number (Enter 1 for day and 2 for night): ')
payRate = input('Hourly Pay Rate: ')
myEmployee = employee.ProductionWorker(name, number,
shift, payRate)
print('--------------------')
print('Employee Information')
print('--------------------')
print('Name:', myEmployee.get_name())
print('Employee Number:', myEmployee.get_number())
print('Customer number:', myEmployee.get_Shift())
print('Hourly Pay Rate:', myEmployee.get_payRate())
好的,固定类型:
myEmployee = employee.Employee(name, number,
shift, payRate)
为:
myEmployee = employee.ProductionWorker(name, number,
shift, payRate)
但现在我收到了这个错误:
Traceback (most recent call last):
File "C:/Users/Alex/Desktop/Programming Concepts/Homework 2/Chapter 13/Employee and Production Worker Class.py", line 9, in <module>
shift, payRate)
File "C:/Users/Alex/Desktop/Programming Concepts/Homework 2/Chapter 13\employee.py", line 24, in __init__
Employee.__init__(self, name, number)
File "C:/Users/Alex/Desktop/Programming Concepts/Homework 2/Chapter 13\employee.py", line 5, in __init__
self.__number - number
AttributeError: 'ProductionWorker' object has no attribute '_Employee__number'
再次感谢您的帮助!
答案 0 :(得分:7)
更改
myEmployee = employee.Employee(name, number,
shift, payRate)
到
myEmployee = employee.ProductionWorker(name, number,
shift, payRate)
另外,一条建议:写一个getter和setter通常是frowned upon in Python。只需将成员公开并获取/设置它们:
myEmployee.name = "David"
print myEmployee.name
答案 1 :(得分:2)
只需更改以下行:
myEmployee = employee.Employee(name, number,
shift, payRate)
到
myEmployee = employee.ProductionWorker(name, number,
shift, payRate)
我想这可能只是一个错字......
答案 2 :(得分:2)
您误将Employee
误认为主代码中的ProductionWorker
。
替换
myEmployee = employee.Employee(name, number,shift, payRate)
通过
myEmployee = employee.ProductionWorker(name, number,shift, payRate)