【问题标题】:How to call super in an initialize method when both class inheritance and Module include is being used?当同时使用类继承和模块包含时,如何在初始化方法中调用 super?
【发布时间】:2012-07-17 19:23:49
【问题描述】:

如果我有一个与类继承一起包含的模块,那么外观路径如何决定在哪里调用“超级”。我的预感是默认情况下它将使用模块中的初始化方法。它是否正确?如果是这样,我如何明确告诉代码使用继承类中的初始化方法?

下面是一个例子:

我希望 Employee 类从 Other 而不是 Subject 继承初始化。

  module Subject
    def initialize
      @observers = []
    end
  end

  class Other
    def initialize
      @other_stuff = []
    end
  end

  class Employee < Other
    include Subject 

    attr_reader :name

    def initialize(name)
     super()
    end
  end

【问题讨论】:

    标签: ruby inheritance superclass


    【解决方案1】:

    我的预感是默认情况下它会使用模块中的初始化方法。

    正确。如果一个类包含一个模块,那么该模块的方法将替换继承的同名方法。

    如果是这样,我如何明确告诉代码使用继承类中的初始化方法?

    你可能最好进行重构,这样你就不会遇到这个问题。

    但是,有几种方法可以让 Other 的初始化方法被调用,而不是 Subject 的。

    这样的事情怎么样:

    module Subject
      def initialize
        puts "subject initialize"
        @observers = []
      end
    end
    
    class Other
      def initialize
        puts "other initialize"
        @other_stuff = []
      end
    end
    
    class Employee < Other
    
      alias_method :other_initialize, :initialize
    
      include Subject
    
      attr_reader :name
    
      def initialize(name)
        other_initialize
      end
    end
    
    Employee.new('test')
    

    如果你运行它,你会看到 Other 的初始化方法被调用了。然而,编写这样的代码并不是一个好主意。

    【讨论】:

    • 谢谢!这无疑为我澄清了一些事情。
    猜你喜欢
    • 2021-06-30
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    • 2018-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    相关资源
    最近更新 更多