0

I have just learned that super() allows you to call a method in a base class from within the overridden method in a subclass. But can you please explain to me with a good example?

4

1 回答 1

1

通常你可以直接调用父类的方法 do Parent.foo(self, ...),但是在多重继承的情况下,super()更有用;此外,即使使用单继承,也super()可以通过不强迫您将父类硬编码到子类中来帮助您,因此如果您更改它,调用 usingsuper()将继续工作。

class Base(object):
    def foo(self):
        print 'Base'


class Child1(Base):
    def foo(self):
        super(Child1, self).foo()
        print 'Child1'


class Child2(Base):
    def foo(self):
        super(Child2, self).foo()
        print 'Child2'



class GrandChild(Child1, Child2):
    def foo(self):
        super(Child2, self).foo()
        print 'GrandChild'

Base().foo()
# outputs:
# Base

Child1().foo()
# outputs:
# Base
# Child1

Child2().foo()
# outputs:
# Base
# Child2

GrandChild().foo()
# outputs:
# Base
# Child1
# Child2
# GrandChild

您可以在文档中找到更多信息,并通过谷歌搜索“钻石继承”或“钻石继承 python”。

于 2013-09-01T13:42:14.310 回答