美文网首页
python2 和 python3 中调用父类方法

python2 和 python3 中调用父类方法

作者: wangtieshan | 来源:发表于2017-08-15 10:27 被阅读0次

首先把自己碰到的错误贴出来:

TypeError: super() takes at least 1 argument (0 given)

首先看 python2 中的写法

class Animal(object):

    def __init__(self):
        print 'Animal init'

class Tom(Animal):

    def __init__(self):

        '''第一种写法:'''
        super(Tom, self).__init__()

        '''第二种写法'''
        Animal(self),__init__()

        print('Tom init')

从上面代码看,可知共两种写法

                '''第一种写法:'''
        super(Tom, self).__init__()

        '''第二种写法'''
        Animal(self),__init__()

先看第二种写法,就是 Animal 类通过 self 初始化了一个对象(实例、instance),然后让该对象调用器 init 方法。
第二种写法不难理解

然后第一种写法其实就是写法不同,但是可以这么理解
super(Tom, self) 就是查找 Tom.super -> Animal
然后使用 Animal(self) 调用 init 方法

python3

python3 中写法更为简单,第二种写法,在python2 和 python3 中都可以使用
然后 python3 中可以直接 super().method 调用方法

相关文章

  • 【第24天】python全栈从入门到放弃

    1 python2和python3区别 2 类方法: @classmethod 3 通过类方法调用(可以不用对象调...

  • python2 和 python3 中调用父类方法

    首先把自己碰到的错误贴出来: 首先看 python2 中的写法 从上面代码看,可知共两种写法 先看第二种写法,就是...

  • python类继承(super多类继承)

    1. python2和python3中定义类的形式不同 python3中只有只有新式类 python2中有经典类和...

  • Super

    编译器的指令符号如果想在子类调用父类的方法使用Super在类方法中调用父类的类方法在对象方法调用父类的对象方法可以...

  • JavaScript零散知识点

    继承 super 在子类中调用super,会调用父类的方法; 不用super,则会覆盖父类的方法。调用本类中的方法。

  • Python调用父类中的方法和super()的用途

    直接调用父类的super方法 调用父类的init()方法,确保父类被正确初始化 当覆盖了python中的特殊方法时

  • python 面向对象: super()

    python 关于 super 的使用 子类对象调用父类方法 :super(B,b).hh() 子类中调用父类方法...

  • 继承类的容易出错的基础题

    结论:子类继承父类,调用方法时先是调用子类中的方法,如果没有就调用父类中的方法,还有一点就是try{ }、catc...

  • iOS 小知识点总结

    子类实现父类方法时,监测子类是否调用super方法。 在父类中声明方法时: 子类中实现该父类方法: 图片压缩

  • 继承

    super() 用于调用父类的构造方法 this() 用于调用本类中的构造方法 覆盖 覆盖父类的方法 应保持与...

网友评论

      本文标题:python2 和 python3 中调用父类方法

      本文链接:https://www.haomeiwen.com/subject/ksjmrxtx.html