Calling an overridden method, superclass an calls overridden method

后端 未结 4 1927
情深已故
情深已故 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 01:09

    In class A instead of calling self methods you need to call A methods and pass in self manually.

    This is not the normal way of doing things -- you should have a really good reason for doing it like this.

    class A(object):
        def foo(self):
            print A.foo1(self)
    
        def foo1(self):
            return "foo"
    
    class B(A):
        def foo1(self):
            raise AttributeError, "wtf!"
    
        def foo(self):
            raise AttributeError, "wtf!"
    
        def foo2(self):
            super(B, self).foo()
    
    myB = B()
    myB.foo2()
    

提交回复
热议问题