【问题标题】:Ruby Inheritance - Super Initialize getting wrong number of argumentsRuby 继承 - 超级初始化获取错误数量的参数
【发布时间】:2011-12-03 03:11:13
【问题描述】:

我正在使用 Ruby 并学习 OO 技术和继承,我终于遇到了一个让我困扰了一段时间的错误。

人员类

class Person
    attr_accessor :fname, :lname, :age

    def has_hat?
        @hat
    end

    def has_hat=(x)
        @hat = x
    end

    def initialize(fname, lname, age, hat)
        @fname = fname
        @lname = lname
        @age = age
        @hat = hat
    end

    def to_s
        hat_indicator = @hat ? "does" : "doesn't"
        @fname + " " + @lname + " is " + @age.to_s + " year(s) old and " + hat_indicator + " have a hat\n"  
    end

    def self.find_hatted()
        found = []
        ObjectSpace.each_object(Person) { |p|
            person = p if p.hat?
            if person != nil
                found.push(person)              
            end
        }
        found
    end

end

程序员类(从 Person 继承)

require 'person.rb'

class Programmer < Person
    attr_accessor :known_langs, :wpm

    def initialize(fname, lname, age, has_hat, wpm)
        super.initialize(fname, lname, age, has_hat)
        @wpm = wpm
        @known_langs = []
    end

    def is_good?
        @is_good
    end

    def is_good=(x)
        @is_good = x
    end

    def addLang(x)
        @known_langs.push(x)
    end


    def to_s
        string = super.to_s
        string += "and is a " + @is_good ? "" : "not" + " a good programmer\n"
        string += "    Known Languages: " + @known_languages.to_s + "\n"
        string += "    WPM: " + @wpm.to_s + "\n\n"
        string
    end

end

然后在我的主脚本中这行失败了

...
programmer = Programmer.new('Frank', 'Montero', 46, false, 20)
...

出现这个错误

./programmer.rb:7:in `initialize': wrong number of arguments (5 for 4) (ArgumentError)
        from ./programmer.rb:7:in `initialize'
        from ruby.rb:6:in `new'
        from ruby.rb:6:in `main'
        from ruby.rb:20

【问题讨论】:

    标签: ruby oop inheritance constructor


    【解决方案1】:

    程序员初始化应该是-

    def initialize(fname, lname, age, has_hat, wpm)
        super(fname, lname, age, has_hat)
        @wpm = wpm
        @known_langs = []
    end
    

    【讨论】:

      【解决方案2】:

      使用所需参数调用 super,而不是调用 super.initialize。

      super(fname, lname, age, has_hat)
      

      【讨论】:

      • 特别注意:我的父类没有参数,它的子类有一个。我一直想知道为什么孩子的super 将它的参数从initialize 传递给Parent.initialize,当我意识到我应该使用super() 时,它显式调用具有no arguments 的父类.
      • @Doogans:谢谢!带有显式括号的 super() 与 super 不同。
      猜你喜欢
      • 1970-01-01
      • 2016-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多