ruby - 当从子调用父方法时,从父调用子方法
问题描述
有 2 个 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
类的。我希望从(ie ) 调用时,它将使用. 相反,它使用. 这是可以理解的,但不可取。Parent
Child
super
Child
Child.method2
method1
Child
method1
Parent
如何解决?
解决方案
所以我用一些 put 运行了你的代码:
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 处理方法解析,目标始终是对象的类。在上面的代码中,即使使用 super 调用,该类仍然是子类。所以它会调用定义在子级上的任何方法,如果没有找到,然后在父级上调用,或者如果子级调用超级......
推荐阅读
- sql - 将 MS SQL 服务器与 Google Data Studio 连接的最佳方式是什么?
- c - C结构自释放
- android - 如何解析 http 异常 401 上的成功正文响应?
- xamarin.forms - Xamarin Forms -> Activity Indicator not working if statements of statements to be executed
- google-chrome-extension - 如何从 chrome 扩展程序中询问谷歌密码?
- postgresql - 如何在 Haskell 中使用 postgresql-simple 插入 bytea 值
- php - 创建了数据库记录,但未插入具有键值对数据的数组 - json php
- python - ImportError:没有名为 redis 的模块 - Docker
- java - 如果调用 scheduleWithFixedDelay 方法的次数超过池大小,ScheduledExecutorService 如何工作?
- javascript - 如何更改 JavaScript 中的舍入规则?