有两个Ruby类:
class Parent
class << self
def method1
...
end
def method2
...
method1
...
end
end
end
class Child < Parent
class << self
def method1
...
end
def method2
...
super
end
end
end类Child是从Parent继承的,并重新定义了它的方法method1和method2。Method2类Parent是从Child中的相同方法调用的(使用super关键字)。我希望当从Child (即Child.method2)调用时,它将使用method1 of Child。相反,它使用method1 of Parent。这是可以理解的,但不可取。
怎么修呢?
发布于 2019-01-10 20:13:27
所以我运行了你的代码,并给出了一些建议:
class Parent
class << self
def method1
puts "parent.method1; self: #{self.inspect}"
end
def method2
puts "parent.method2 before method1 call; self: #{self.inspect}"
method1
puts "parent.method2 after method1 call"
end
end
end
class Child < Parent
class << self
def method1
puts "child.method1; self: #{self.inspect}"
end
def method2
puts "child.method2 before super; self: #{self.inspect}"
super
puts "child.method2 after super"
end
end
end
Child.method2这就是我得到的:
输出
child.method2 before super; self: Child
parent.method2 before method1 call; self: Child
child.method1; self: Child
parent.method2 after method1 call
child.method2 after super这不是你想要的吗?
Ruby处理方法解析,目标总是对象的类。在上面的代码中,即使在使用超级调用时,类仍然是子类。因此,它将调用定义在子上的任何方法,如果没有找到,则调用父方法,或者如果子方法调用超级.
https://stackoverflow.com/questions/54136050
复制相似问题