class Test:
def __init__(self, name, age):
self.name = name
self.age = age
class Test1:
def __init__(self, school, university):
self.school = school
self.university = university
def get(self):
print('josh')
class Test2(Test,Test1):
def __init__(self, name1, age1, school1, university1):
super().__init__(name = name1, age = age1 , school = school1, university = university1)
t = Test2('john', 16, 'Harvard', 'Yale')
为什么不能将值分配给父类属性?例如,对于上述课程,为什么我不能执行以下课程?
t.school # returns error
t.university #returns error
但是,以下有效吗?
t.name
t.age
我想完全依靠超级功能来实现这一目标。
答案 0 :(得分:0)
您必须为每个基类调用构造函数。请参见此处:
class Test:
def __init__(self, name, age):
self.name = name
self.age = age
class Test1:
def __init__(self, school, university):
self.school = school
self.university = university
def get(self):
print('josh')
class Test2(Test,Test1):
def __init__(self, name1, age1, school1, university1):
Test.__init__(self, name1, age1)
Test1.__init__(self, school1, university1)
t = Test2('john', 16, 'Harvard', 'Yale')
print(t.name)
print(t.age)
print(t.school)
print(t.university)
答案 1 :(得分:0)
我找到了一个解决方案-这仅依赖于使用super函数初始化所有(父类)属性。
class Test:
def __init__(self, name, age, **kwargs):
self.name = name
self.age = age
super().__init__(**kwargs)
class Test1:
def __init__(self, school, university, **kwargs):
self.school = school
self.university = university
super().__init__(**kwargs)
def get(self):
print('josh')
class Test2(Test,Test1):
def __init__(self, name1, age1, school1, university1, **kwargs):
kwargs['name'] = name1
kwargs['age'] = age1
kwargs['school'] = school1
kwargs['university'] = university1
super().__init__(**kwargs)
t = Test2('john', 16, 'Harvard', 'Yale')
print(t.name)
print(t.age)
print(t.school)
print(t.university)