为了账号安全,请及时绑定邮箱和手机立即绑定

子类使用super调用父类初始化方法,父类一定要继承自object吗

子类使用super调用父类初始化方法,父类一定要继承自object吗

神经性bug 2017-01-23 22:31:11
源码:class TestBaseClassFather():     def __init__(self,name,age):         self.name = name         self.age = age class TestBaseClassExtendChild(TestBaseClassFather):     def __init__(self,name,age,major):         super(TestBaseClassExtendChild, self).__init__(name,age)         self.major = major此时报错:bash-3.2$ python base_1/3_class.py  Traceback (most recent call last):   File "base_1/3_class.py", line 175, in <module>     testMulitExtend()   File "base_1/3_class.py", line 164, in testMulitExtend     basChild = TestBaseClassExtendChild("zhangsan",23,"shuxue")   File "base_1/3_class.py", line 153, in __init__     super(TestBaseClassExtendChild, self).__init__(name,age) TypeError: must be type, not classobj接着写上object:class TestBaseClassFather(object):     '''     此处必须写上继承自object     '''     def __init__(self,name,age):         self.name = name         self.age = age class TestBaseClassExtendChild(TestBaseClassFather):     def __init__(self,name,age,major):         super(TestBaseClassExtendChild, self).__init__(name,age)         self.major = major执行结果正常:['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'major', 'name'] <class '__main__.TestBaseClassExtendChild'> True {'age': 23, 'name': 'zhangsan', 'major': 'shuxue'}
查看完整描述

1 回答

已采纳
?
代沟000

TA贡献2条经验 获得超0个赞

    1)多成继承会涉及到查找顺序(MRO),经典类和新式类的查找方式不一样。

    2)在多继承中,新式类采用广度优先搜索,而旧式类(经典类)是采用深度优先搜索。

    3)新式类更符合OOP编程思想,统一了python中的类型机制。

查看完整回答
反对 回复 2017-01-24
  • 1 回答
  • 0 关注
  • 1707 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信