0

Tough for me to find a good title for this problem. Please refer to code.

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]}}}

Pretty much I want to be able access the Student parameter 'attendance' using both the Student and Child object within the School instance.

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

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

I want the last line to print True since I set schools[1].student[1].attendance, but its printing False. How do I map it so when i set the child['Tim'] object, its the same as setting the student[1] object. student[1] and child['Tim'] should be mapped to the same Student object's parameter.

Is this even possible?

navy_green
  • 83
  • 2
  • 7

1 Answers1

0

You need to call the Student constructor from the Child one to initialized its attributes. You can do this with super (a requirement in multiple inheritance scenarios) or use the Student class explicitly.

Example using super:

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

Probably you also want to remove the duplicated id attribute from the Child class.

For more info on super: Understanding Python super() with __init__() methods

Community
  • 1
  • 1
Lauro Moura
  • 750
  • 5
  • 15
  • Also, on the class hierarchy from the question, you could instantiate just one `child` object and refer to it from both child and student arrays, as every `Child` object is also a `Student` one. – Lauro Moura Mar 29 '16 at 16:23
  • super().__init__(student_info, student_id) raises 'TypeError: super() takes at least 1 argument (0 given)' – navy_green Mar 29 '16 at 17:05
  • I tried super(Child,self).__init__(student_info, student_id) and Student(object), using super doesn't seem to work. – navy_green Mar 29 '16 at 17:16
  • Sorry, the `super()` (no args) is a Python 3 feature. In Python 2 you need to use the second form (with the explicit class) but the class you put in super is the class where you call the super, in this case, `Child`, not the parent one. Think of it something like "I need the super class of Child" – Lauro Moura Mar 29 '16 at 19:50