我是编码的新手-学习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')
最佳答案
ProductionWorker
类是Employee
类的子类,但这并不意味着您可以通过Employee
的实例来调用它。它仍然是您应该直接调用的顶级类。尝试仅用employee.ProductionWorker(...)
替换ProductionWorker(...)
。
您将克服当前的错误,但是您可能会遇到新的错误。例如,我认为当前从Employee.__init__
调用ProductionWorker.__init__
的尝试将失败,因为它没有传递正确数量的参数。如果您期望employee.ProductionWorker
创建以某种方式与ProductionWorker
对象相关的employee
实例,则您可能还会遇到逻辑问题。
我也劝阻您不要使用__double_leading_underscore
名称作为属性。这将调用Python的名称处理系统,该系统主要旨在帮助防止在大型或不可预测的继承层次结构中意外地重用不同类中的相同名称。如果只希望属性为“私有”,请使用单个下划线。这并不能防止它们被外部代码访问,但是可以作为文档,证明它们不是对象公共API的一部分。 Python的设计哲学之一是,程序员应对自己的行为负责(通常用“我们都是成年人”来形容)。如果程序员想要访问对象的私有数据,则可以这样做(这对于调试非常有用)。但是,如果他们破坏了东西,除了他们自己,他们没有人要责怪。