调用重写方法,超类调用重写方法 [英] Calling an overridden method, superclass an calls overridden method

查看:128
本文介绍了调用重写方法,超类调用重写方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码抛出异常 AttributeError,wtf!,因为 A.foo()正在调用 B.foo1(),不应该调用 A.foo1()?如何强制它调用 A.foo1()(以及 A.foo()内的任何方法调用都应该致电$ code> A。* )

This code throws an exception, AttributeError, "wtf!", because A.foo() is calling B.foo1(), shouldn't it call A.foo1()? How can I force it to call A.foo1() (and any method call inside A.foo() should call A.*)

class A(object):
    def foo(self):
        print self.foo1()

    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()


推荐答案

它按预期工作,占世界的100%编程语言工作。子类覆盖父类的所有方法。

It is working as intended, as 100% of world programming languages work. Subclass overrides ALL methods of parent class.

但是如果你真的想要调用A.foo1(),你可能会这样做(我无法保证) )。无论如何你不能这样做,因为这违反了良好编程的所有原则。

However if you really really want to call the A.foo1() you might be able to do it like this (I cannot guarantee). And in any case you must not do this as this is against all principles of good programming.

 class A(object):

    def foo(self):
        A.foo1(self)

这篇关于调用重写方法,超类调用重写方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆