首页 > 解决方案 > 当从子调用父方法时,从父调用子方法

问题描述

有 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并重新定义其方法method1method2. 从(使用关键字)中的相同方法调用Method2类的。我希望从(ie ) 调用时,它将使用. 相反,它使用. 这是可以理解的,但不可取。ParentChildsuperChildChild.method2method1Childmethod1Parent

如何解决?

标签: ruby

解决方案


所以我用一些 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 调用,该类仍然是子类。所以它会调用定义在子级上的任何方法,如果没有找到,然后在父级上调用,或者如果子级调用超级......


推荐阅读