繁体   English   中英

从超类调用子类的方法

[英]Call subclass's method from superclass

我对Python继承有点陌生。

我希望子类从超类继承,并且我希望超类中的方法调用子类中的方法。

在Ruby中,这可以正常工作:

class A
  def foo
    self.bar
  end
end

class B < A
  def init
    foo
  end

  def bar
    puts "I, Bar"
  end
end

B.new.bar

运行此程序时,正如我期望的那样,我看到“ I,Bar”。

但是,在Python中,我认为等效的代码表现得很奇怪:

class A:
    def foo(self):
        self.bar()

class B(A):
    def __init__(self):
        self.foo()

    def bar(self):
        print "I, Bar"

B().bar()

当我运行时,看到打印两次 “ I,Bar”。

如何用Python重写Ruby代码? 有可能吗?如果可以,我在做什么错?

在Python中,通常会在创建对象(如在Ruby中initialize时调用__init__方法。 因此,请使用其他名称重命名__init__方法。

我认为您在Ruby代码中输入了错误的init而不是进行initialize

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM