创建一个继承自 Ruby 中另一个类的类 [英] Creating a class which inherits from another class in Ruby

查看:48
本文介绍了创建一个继承自 Ruby 中另一个类的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个名为 Musician 的类,该类继承自我的类 Person,然后添加了一个乐器属性.我知道我的 Musician 类是错误的,但我只是想知道 Ruby 中的正确格式是什么.这是我所有的代码:

I'm trying to create a class called Musician which inherits from my class Person and then adds an instrument attribute. I know my Musician class is wrong, but I just wanted to know what the correct format is in Ruby. Here is all of my code:

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

p = Person.new("Earl", "Rubens-Watts", 2)
p.first_name
p.last_name
p.age


class Musician < Person
  attr_reader :instrument
  def initialize (instrument)
    @instrument = instrument
  end
end

m = Musician.new("George", "Harrison", 58, "guitar")
m.first_name + " " + m.last_name + ": " + m.age.to_s
m.instrument

感谢您的帮助!

推荐答案

如果您希望在 Musician 中使用 first_name、last_name 和 age,那么您必须将它们包含在初始值设定项中并利用 super.类似的东西:

If you want first_name, last_name and age to be available in Musician then you must include them in the initializer and take advantage of super. Something like:

class Musician < Person
  attr_reader :instrument

  def initialize(first_name, last_name, age, instrument)
    super(first_name, last_name, age)
    @instrument = instrument
  end
end

super 在父类内部调用同名方法.

super calls the method with the same name inside of the parent class.

更新

我会把重点带回家.在这种完全虚构的情况下,您也可以使用 super:

I will drive the point home. You would also use super in this totally made up situation:

class GuitarPlayer < Person
  attr_reader :instrument

  def initialize(first_name, last_name, age)
    super(first_name, last_name, age)
    @instrument = 'guitar'
  end
end

我们没有改变初始化的参数,但我们扩展了行为.

We haven't changed the arguments to initialize but we have extended the behavior.

这篇关于创建一个继承自 Ruby 中另一个类的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆