如何在Python中将两个子对象相互映射

时间:2016-03-29 16:06:08

标签: python oop

我很难找到这个问题的好标题。请参阅代码。

class School:
     def __init__(self, info):
         self.name = info['name']
         self.student = info['students']
         for x in self.student:
             self.child[self.student[0]] = Child(x, self.student[x])
             self.student[x] = Student(x, self.student[x])

class Student:
     def __init__(self, student_info, student_id):
         self.id = student_id
         self.name = student_info[0]
         self.age = student_info[1] 
         self.sex = student_info[2] 
         self.attendance = False 

class Child(Student)
     def __init__(self, student_info, student_id):
         self.id = student_info[0]
         self.student_id = student_id        

schools = {1:{'name':'Hard Knocks', 'students':{1:['Tim',12,M], 2:['Kim',11,M]}}}

我希望能够使用School实例中的Student和Child对象访问Student参数'attendance'。

#instantiating
for x in students:
    schools[x] = School(schools[x])

schools[1].student[1].attendance = True
print schools[1].child['Tim'].attendance

我希望最后一行打印为True,因为我设置了学校[1] .student [1] .attendance,但其打印错误。当我设置子['Tim']对象时,如何映射它,它与设置student [1]对象相同。 student [1]和child ['Tim']应该映射到同一个Student对象的参数。

这甚至可能吗?

1 个答案:

答案 0 :(得分:0)

您需要调用Student中的Child构造函数来初始化其属性。您可以使用super(多个继承方案中的要求)或显式使用Student类来执行此操作。

使用super:

的示例
class Child(Student)
  def __init__(self, student_info, student_id):
    super().__init__(student_info, student_id)
    ...

您可能还希望从id类中删除重复的Child属性。

有关super:Understanding Python super() with __init__() methods

的更多信息