我有一个带有Manager类的Employee类,每个创建的员工都将获得Employee类的属性,甚至是Manager。
我的问题是,我想创建一个输入选项,要求经理输入他想要添加到其监督中的员工(将其添加到员工列表中),并将员工属性添加为好 (我知道最后3行是错的,我只是想不出来。)
class Employee:
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first+'.'+last+'@company.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
class Manager(Employee):
def __init__(self,first,last,pay,employees=None):
super().__init__(first,last,pay)
if employees is None:
self.employees = []
else:
self.employees = employees
def add_emps(self,emp):
if emp not in self.employees:
self.employees.append(emp)
else:
print('the employee is already in your supervise')
def print_emps(self):
for em in self.employees:
print('-->',em.fullname())
emp_1 = Employee('Mohamad','Ibrahim',90000)
emp_2 = Employee('Bilal','Tanbouzeh',110000)
emp_3 = Employee('Ghalia','Awick',190000)
emp_4 = Employee('Khaled','Sayadi',80000)
mngr_1 = Manager('Ibrahim','othman',200000,[emp_1,emp_2])
mngr_2 = Manager('Rayan','Mina',200000,[emp_3,emp_4])
add_them = input('enter the employee you would like to add')
mngr_1.add_emps(add_them)
mngr_1.print_emps()
答案 0 :(得分:1)
如果你不熟悉字典,我会给你一个快速的故事,但你应该阅读PyDocs,以及Hash Tables上的一般维基百科条目。
a = {} # create an empty dictionary
a['some_key'] = "Some value" # Equivalent of creating it as a = {'some_key': "Some value"}
# Dictionaries are stored in "key, value pairs" that means one key has one value.
# To access the value for a key, we just have to call it
print(a['some_key'])
# What if we want to print all values and keys?
for key in a.keys():
print("Key: " + key + ", Value: " + str(a[key]))
现在回答你的实际问题。我构建了一份员工字典,并从字典中将员工的密钥添加到了经理。我还展示了构建字典的两种方法:一种是在创建dict
时添加值,另一种是在以后添加值。
class Employee:
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first+'.'+last+'@company.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
class Manager(Employee):
def __init__(self,first,last,pay,employees=None):
super().__init__(first,last,pay)
if employees is None:
self.employees = []
else:
self.employees = employees
def add_emps(self,emp):
if emp not in self.employees:
self.employees.append(emp)
else:
print('the employee is already in your supervise')
def print_emps(self):
for em in self.employees:
print('-->',em.fullname())
employee_dict = {
'Mohamad_Ibrahim': Employee('Mohamad','Ibrahim',90000),
'Bilal_Tanbouzeh': Employee('Bilal','Tanbouzeh',110000)
}
employee_dict['Ghalia_Awick'] = Employee('Ghalia','Awick',190000)
employee_dict['Khaled_Sayadi'] = Employee('Khaled','Sayadi',80000)
mngr_1 = Manager('Ibrahim','othman',200000,[employee_dict['Mohamad_Ibrahim'],employee_dict['Bilal_Tanbouzeh']])
mngr_2 = Manager('Rayan','Mina',200000,[employee_dict['Ghalia_Awick'],employee_dict['Khaled_Sayadi']])
add_them = input('enter the employee you would like to add') # Expects the name like the keys are Firstname_Lastname
mngr_1.add_emps(employee_dict[add_them])
mngr_1.print_emps()