What's the difference between super().method() and self.method()

后端 未结 2 1950
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-23 03:23

What\'s the difference between using super().method() and self.method(), when we inherit something from a parent class and why use one instead of anoth

2条回答
  •  無奈伤痛
    2021-01-23 03:59

    super().method() will call the parent classes implementation of method, even if the child has defined their own. You can read the documentation for super for a more in-depth explanation.

    class Parent:
        def foo(self):
            print("Parent implementation")
    
    class Child(Parent):
        def foo(self):
            print("Child implementation")
        def parent(self):
            super().foo()
        def child(self):
            self.foo()
    
    c = Child()
    c.parent()
    # Parent implementation
    c.child()
    # Child implementation
    

    For singular-inheritance classes like Child, super().foo() is the same as the more explicit Parent.foo(self). In cases of multiple inheritance, super will determine which foo definition to use based on the Method Resolution Order, or MRO.

    A further motivating example: which method gets called if we subclass Child and write another implementation of foo?

    class Grandchild(Child):
        def foo(self):
            print("Grandchild implementation")
    
    g = Grandchild()
    g.parent()
    # Parent implementation
    g.child()
    # Grandchild implementation
    

提交回复
热议问题