我有两个不同的对象。其中一个在列表或元组属性中包装了 N 个其他类型的对象。假设教室里的学生:
class Student:
def __init__(self, name):
self.name = name
class ClassRoom:
def __init__(self, students):
self.students = students
当然,我们有大量 Student 和 ClassRoom 实例:
john, sam = Student('John'), Student('Sam')
patrick, michael, bill = Student('Patrick'), Student('Michael'), Student('Bill')
klass1 = ClassRoom([john, sam])
klass2 = ClassRoom([patrick, michael, bill])
只需考虑每个学生的名字都是独一无二的,并且您无法通过引用访问学生的教室,如下所示:
sam.get_classroom() # Student class doesn't support this :(
我们有一个辅助函数来完成这项工作:
def get_classroom_by_student(klasses, student_name):
for klass in klasses:
for student in klass.students:
if student.name==student_name:
return klass
# Or yield if a student belongs to more than one class
sams_class = get_classroom_by_student([klass1, klass2], 'Sam')
bills_class = get_classroom_by_student([klass1, klass2], 'Bill')
既然“平面优于嵌套”,我该如何创建一个高效的生成器,或者是否有一些 Python 的方法来实现这个辅助函数?