[英]Call subclass's method from superclass
I am a bit new to Python inheritance. 我对Python继承有点陌生。
I want a subclass to inherit from a superclass, and I want a method in the superclass to call a method in the subclass. 我希望子类从超类继承,并且我希望超类中的方法调用子类中的方法。
In Ruby, this works fine: 在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
When I run this, I see "I, Bar", as I expected. 运行此程序时,正如我期望的那样,我看到“ I,Bar”。
In Python, however, what I thought to be equivalent code behaves strangely: 但是,在Python中,我认为等效的代码表现得很奇怪:
class A:
def foo(self):
self.bar()
class B(A):
def __init__(self):
self.foo()
def bar(self):
print "I, Bar"
B().bar()
When I run that I see printed twice "I, Bar". 当我运行时,看到打印两次 “ I,Bar”。
How can I rewrite the Ruby code in Python? 如何用Python重写Ruby代码? Is it possible, and if so, what am I doing wrong? 有可能吗?如果可以,我在做什么错?
In Python __init__
method is normally called whenever an object is created like initialize
in Ruby. 在Python中,通常会在创建对象(如在Ruby中initialize
时调用__init__
方法。 So rename your __init__
method in an other name. 因此,请使用其他名称重命名__init__
方法。
I think you mistyped init
instead of initialize
in your Ruby code. 我认为您在Ruby代码中输入了错误的init
而不是进行initialize
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.