Reputation: 29
I am new to Python and am trying to get more familiar with the object-orientated programming side of the language. I want to try to connect two sub-classes of a single class, using the constructor methods for the sub-class:
Firstly, I make the Employer class like this:
class Employee:
worker_list = []
manager_list= []
## using a constructor to set class
def __init__(self,first_name,last_name,salary):
self.first_name = first_name
self.last_name = last_name
self.salary = salary
self.email = f"{first_name}{last_name}@WHBC.com"
if isinstance(self, Worker) is True:
self.worker_list.append(self)
if isinstance(self, Manager) is True:
self.manager_list.append(self)
## class method for obtaining full name
def fullname(self):
return(f"{self.first_name} {self.last_name}")
I then created the worker sub-class:
class Worker(Employee):
def __init__(self, first_name, last_name, salary,department):
super().__init__(first_name, last_name, salary)
self.department = department
And a manager sub-class:
class Manager(Employee):
def __init__(self, first_name, last_name, salary,department):
super().__init__(first_name, last_name, salary)
self.department = department
self.employees_managed = [worker.fullname() for worker in Employee.worker_list if worker.department ==self.department]
The attribute employees_managed works for any manager instances I create, but when I try to use the same approach with workers, I am unable to create a managed_by attribute for the workers.
Any help would be much appreciated.
Upvotes: 0
Views: 194
Reputation: 264
Because employees_managed
is defined by __init__
. So, previous worker not have later manager's info.
You should use a function, or @property
.
class Worker(Employee):
def __init__(self, first_name, last_name, salary,department):
super().__init__(first_name, last_name, salary)
self.department = department
@property
def managed_by(self):
return [manager for manager in Employee.manager_list if manager.department == self.department]
class Manager(Employee):
def __init__(self, first_name, last_name, salary,department):
super().__init__(first_name, last_name, salary)
self.department = department
@property
def employees_managed(self):
return [worker.fullname() for worker in Employee.worker_list if worker.department ==self.department]
Upvotes: 2