gpt4 book ai didi

python - 我有一个 Employee 类,我想返回一个 'names' 列表

转载 作者:太空宇宙 更新时间:2023-11-04 04:02:21 25 4
gpt4 key购买 nike

我有一个 Employee 类,我想返回一个“姓名”列表。

员工.py
class Employee(object):

def __init__(self, id, name, members=None):
self.id = id
self.name = name
self.members = members
self.is_team = members is not None

使用数据提要,实例创建一个 Employee 对象。

饲料.py
from employee import Employee

anne = Employee(0, 'Anne')
bob = Employee(1, 'Bob')
carlos = Employee(2, 'Carlos')
carol = Employee(3, 'Carol')
charlie = Employee(4, 'Charlie')
cherry = Employee(5, 'Cherry')
dave = Employee(6, 'Dave')
emma = Employee(7, 'Emma')
mary = Employee(8, 'Mary')
peggy = Employee(9, 'Peggy')
trent = Employee(10, 'Trent')

admin = Employee(90, 'Admin', [anne, bob, carlos])
engineering = Employee(91, 'Engineering', [carlos, trent, bob])
catering = Employee(92, 'Catering', [emma, anne, bob])

people = [anne, bob, carlos, carol, charlie, cherry, dave, emma, mary,
peggy, trent, admin, engineering, catering]

到目前为止我的解决方案,

获取名称.py
import feed

def get_names(person, e_list):
try:
for p in e_list:
if p == person and p in e_list:
print(p.name)
except AttributeError:
print('Not found')

print([e.name for e in get_names(feed.carlos, feed.people)])

我希望返回的数据是:

['Admin', 'Catering']

因为卡洛斯属于两者。

最佳答案

我会用 OOP 解决这个问题:

class Employee(object):
def __init__(self, id, name):
self.id = id
self.name = name
self.teams = []

class Team(Employee):
teams = []

def __init__(self, id, name, members):
super().__init__(id, name)
self.members = members
for member in self.members:
member.teams.append(name)
self.__class__.teams.append(self)

@classmethod
def find_employee_teams(cls, person):
found_teams = []
if isinstance(person, str):
for team in cls.teams:
for member in team.members:
if member.name == person:
found_teams.append(team.name)
return found_teams
elif isinstance(person, Employee):
return person.teams
# TODO error handling in case person is neither

carlos = Employee(2, 'Carlos')
admin = Team(90, 'Admin', [carlos])
engineering = Team(91, 'Engineering', [carlos])

print(Team.find_employee_teams('Carlos'))
print(Team.find_employee_teams(carlos))

输出

['Admin', 'Engineering']
['Admin', 'Engineering']


有可能 find_employee_teams 应该在 Employee 而不是 Team 中实现。

关于python - 我有一个 Employee 类,我想返回一个 'names' 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57987959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com