Ruby类实例和继承

时间:2012-06-15 06:38:15

标签: ruby inheritance

除了超类之外,我想创建一个子类来向子类添加属性。这就是我尝试过的:

版本I:

class Person
    attr_reader :first_name, :last_name, :age
    def initialize (first_name, last_name, age) 
        @first_name = first_name  
        @last_name = last_name
        @age = age
    end
end

class Musician < Person
    attr_reader :first_name, :last_name, :age, :instrument
    def initialize (first_name, last_name, age, instrument)
        super 
        @instrument
    end
end

第二版

class Person
    ATTRS = ['first_name', 'last_name', 'age']
    def attributes
        ATTRS
    end
end

class Musician < Person
    ATTRS = ['instrument']
    def attributes
        super + ATTRS
    end
end

这些都不奏效。

1 个答案:

答案 0 :(得分:2)

在版本1中尝试

class Musician < Person
  attr_reader :instrument
  def initialize(first_name, last_name, age, instrument)
     # Pass arguments to the super class' constructor!
     super first_name, last_name, age
     @instrument = instrument
  end
end

感谢attr_reader :first_name, :last_name, :age Person中的Musician因为继承而将拥有这三个访问者。