Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中将两个子对象相互映射_Python_Oop - Fatal编程技术网

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

如何在Python中将两个子对象相互映射,python,oop,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])

很难为这个问题找到一个好的标题。请参考代码

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参数'attention'

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

schools[1].student[1].attendance = True
print schools[1].child['Tim'].attendance
我希望最后一行打印为真,因为我设置了学校[1]。学生[1]。出勤率,但打印为假。当我设置child['Tim']对象时,如何映射它,这与设置student[1]对象相同。学生[1]和子['Tim']应映射到同一学生对象的参数


这可能吗?

您需要从
子类
调用
学生
构造函数来初始化其属性。您可以使用
super
(多继承场景中的一个要求)或显式使用
Student
类来实现这一点

使用super的示例:

class Child(Student)
  def __init__(self, student_info, student_id):
    super().__init__(student_info, student_id)
    ...
您可能还希望从
子类中删除重复的
id
属性


有关super的更多信息:

此外,关于问题中的类层次结构,您可以仅实例化一个
子对象,并从子数组和学生数组中引用它,因为每个
子对象也是一个
学生
一个.super()。\uuu init\uuuuu(student\u info,student\u id)引发“TypeError:super()至少接受1个参数(给定0)'我尝试了super(Child,self).\uuu init(student\u info,student\u id)和student(object),使用super似乎不起作用。很抱歉,
super()
(无参数)是Python 3的功能。在Python2中,您需要使用第二种形式(与显式类一起),但放入super中的类是调用super的类,在本例中是子类,而不是父类。想象一下“我需要超级儿童”