我是编程新手 - 参加Python大学课程。我知道这对你们很多人来说很明显,但我无法弄清楚为什么我继续得到这个错误属性错误:
prodworker = employee.ProductionWorker(shift_num, pay_rate)
AttributeError: 'Employee' object has no attribute 'ProductionWorker'
非常感谢任何帮助:)
class Employee: #writing new class called Employee:
def __init__(self, name, number): #accepts arguments for employee name and
self.__name = name #employee number
self.__number = number
def set_name(self, name): #mutator methods to set name and number
self.__name = name
def set_number(self, number):
self.__number = number
#accessor methods returns name and number
def get_name(self):
return self.__name
def get_number(self):
return self.__number
class ProductionWorker(Employee): #write subclass
def __init__(self, shift_num, pay_rate):
Employee.__init__(self, 'ProductionWorker')
self.__shift_num = shift_num
self.__pay_rate = pay_rate
def set_shift_num(self, shift_num):
self.__shift_num = shift_num
def set_pay_rate(self, pay_rate):
self.__pay_rate = pay_rate
def get_shift_num(self):
return self.__shift_num
def get_pay_rate(self):
return self.__pay_rate
#This program creates an instance of Employee Class
#and an instance of Production Worker Class:
again = 'Y'
while again.upper() == 'Y':
print('Enter the following data for the employee: \n')
name = input('What is the employee name?: ')
number = input('What is the employee number? ')
shift_num = input('What is the employee shift number? 1 = Day, 2 = Night :')
while shift_num != '1' and shift_num != '2':
shift_num = input('Invalid entry! Enter 1 for Day shift or 2 for Night shift!')
else:
if shift_num == '1':
shift_num = 'Day'
if shift_num == '2':
shift_num = 'Night'
pay_rate = float(input('What is the employee pay rate? '))
print()
print('This is an instance of the Employee class:')
employee = Employee(name, number)
print('EMPLOYEE: \t\t'+ employee.get_name())
print('EMPLOYEE NUMBER: \t' + employee.get_number())
print()
print('This is an instance of the Production Worker class: ')
prodworker = employee.ProductionWorker(shift_num, pay_rate)
print('SHIFT: \t\t\t' + ProductionWorker.get_shift_num())
print('PAY RATE: \t\t$' + format(ProductionWorker.get_pay_rate(), ',.2f'), sep='')
print('--------------------------------------------')
again = input('Enter Y to add another: ')
if again.upper() != 'Y':
print('Program End')
答案 0 :(得分:1)
ProductionWorker
类是Employee
类的子类,但这并不意味着您可以通过Employee
的实例调用它。它仍然是一个你应该直接打电话的顶级课程。尝试仅使用employee.ProductionWorker(...)
替换ProductionWorker(...)
。
您将超越当前错误,但您可能会有新错误。例如,我认为当前从Employee.__init__
调用ProductionWorker.__init__
的尝试将失败,因为它没有传递正确数量的参数。如果您希望employee.ProductionWorker
创建一个与ProductionWorker
对象有某种关系的employee
实例,那么您可能也会遇到逻辑问题。
我也不鼓励您使用__double_leading_underscore
名称作为属性。这会调用Python的名称修改系统,该系统主要用于帮助防止意外从大型或不可预测的继承层次结构中的不同类中重用相同的名称。如果您只想将属性设置为“私有”,请使用单个下划线。这并不能保护它们不被外部代码访问,但它可以作为文档,它们不是对象的公共API的一部分。 Python的设计理念之一是它的程序员对自己的行为负责(通常用“我们都同意成年人”这句话来描述)。如果程序员想要访问对象的私有数据,他们可以这样做(这对调试非常有用)。但如果他们破坏了东西,他们就没有人可以责怪自己了。