I’m having trouble with my code. I’m trying to create a subclass which inherits the parent class’s attributes and methods but it doesn’t work. Here’s what I have so far:
class Employee(object):
def __init__(self, emp, name, seat):
self.emp = emp
self.name = name
self.seat = seat
Something is wrong with the block of code below – the subclass.
Do I have to create the __init__ again? And how do I create a new attribute for the subclass. From reading questions, it sounds like __init__ in the subclass will override the parent class – is that true if I call it to define another attribute?
class Manager(Employee):
def __init__(self, reports):
self.reports = reports
reports = []
reports.append(self.name) #getting an error that name isn't an attribute. Why?
def totalreports(self):
return reports
I want the names from the Employee class to be in the reports list.
For example, if I have:
emp_1 = Employee('345', 'Big Bird', '22 A')
emp_2 = Employee('234', 'Bert Ernie', '21 B')
mgr_3 = Manager('212', 'Count Dracula', '10 C')
print mgr_3.totalreports()
I want reports = ['Big Bird', 'Bert Ernie'] but it doesn’t work
You never called the parent class’s
__init__function, which is where those attributes are defined:To do this, you’d have to modify the
Employeeclass’s__init__function and give the parameters default values:Also, this code will not work at all:
reports‘s scope is only within the__init__function, so it will be undefined. You’d have to useself.reportsinstead ofreports.As for your final question, your structure won’t really allow you to do this nicely. I would create a third class to handle employees and managers:
You’d have to add employees to the business by appending them to the appropriate list objects.