How do overridden method calls from base-class methods work?

后端 未结 5 1342
我寻月下人不归
我寻月下人不归 2021-02-18 13:01

According to the docs on inheritance:

Derived classes may override methods of their base classes. Because methods have no special privileges when calling

5条回答
  •  梦如初夏
    2021-02-18 13:52

    Here's the example you requested. This prints chocolate.

    class Base:
        def foo(self):
            print("foo")
        def bar(self):
            self.foo()
    
    class Derived(Base):
        def foo(self):
            print("chocolate")
    
    d = Derived()
    d.bar()  # prints "chocolate"
    

    The string chocolate is printed instead of foo because Derived overrides the foo() function. Even though bar() is defined in Base, it ends up calling the Derived implementation of foo() instead of the Base implementation.

提交回复
热议问题