Calling an overridden method, superclass an calls overridden method

后端 未结 4 1833
情深已故
情深已故 2021-01-08 00:39

This code throws an exception, AttributeError, \"wtf!\", because A.foo() is calling B.foo1(), shouldn\'t it call A.foo1()? Ho

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-08 00:56

    In the code:

    def foo2(self):
        super(B, self).foo()
    

    self is an instance of B.

    When a method derived from A is called by an instance of B it will start looking in the namespace from B, and only if the method is not found (e.g. is not overridden by B) the implementation from A is used, but always with self referring to B. At no point self is an instance of A.

提交回复
热议问题