Python super(Class, self).method与super(Parent, self).method的区别

11 投票
1 回答
11247 浏览
提问于 2025-04-17 15:03

这个问题来源于以下的问题,假设有一个class B是从class A继承过来的。

class A(object):
  def do_work(self):
    print 123

class B(A):
  def do_work(self):
    super(B,self).do_work() # versus the next statement
    super(A,self).do_work() # what's the difference?

1 个回答

20
super(B,self).do_work()

将会调用由类 B 的父类所定义的 do_work 函数,也就是 A.do_work


super(A,self).do_work()

将会调用由类 A 的父类所定义的 do_work 函数,也就是 object.do_work(这个函数可能并不存在,所以很可能会出现错误)。

撰写回答