Python中子类如何调用父类的方法

class FooParent(object):
    def __init__(self):
        print 'Parent'
    def test(self):
        print 'foo parent'

class FooChild(FooParent):
    def bar(self):
        test()

if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar()

运行报错:

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    fooChild.bar() 
  File "test.py", line 9, in bar
    test() 
NameError: global name 'test' is not defined

那么要怎么在子类中调用父类的方法呢:

class FooParent(object):
    def __init__(self):
        print 'Parent'
    def test(self):
        print 'foo parent'

class FooChild(FooParent):
    def bar(self):
        self.test()
        FooParent.test(self)
        super(FooChild, self).test()


if __name__ == '__main__':
    fooChild = FooChild()
    fooChild.bar()

python跟C++有点类似,不像java那样所有的方法都是某个类的属性,由于有全局变量,所以在子类中调用父类的方法必须使用self

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 32,120评论 18 399
  • 要点: 函数式编程:注意不是“函数编程”,多了一个“式” 模块:如何使用模块 面向对象编程:面向对象的概念、属性、...
    victorsungo阅读 5,514评论 0 6
  • 本想着坚持下去该写什么了?是个挺难的主题,毕竟自己不是爬格子的料。先不管形式主题了,先爬满再说吧! 还是继续孩子学...
    洛泓阅读 2,187评论 0 1
  • 1阅读书目:《思考致富》 2阅读时间:45分钟(7:45_8:30) 3阅读内容:第8、9章节 4阅读中遇到的问题...
    浸夜梅花香阅读 819评论 0 0
  • Nice to meet you我的小伙伴,第五期的读写同桌,第六期的读写队友Jasmine——笑笑同学! 很高兴...
    梁木纯阅读 3,701评论 1 5