0

我试图理解继承:

class Car
  @@wheels = 4
  def wheel
    @@wheels
  end
end

class StretchLimo < Car
  @@wheels = 6
  def whee
    @@wheels
  end
  def turn_on_television
  end
end

我像这样实例化一些对象:

moe = Car.new
larry = StretchLimo.new

当我这样做时moe.wheel,我得到6,当我期待时4

我正在关注的 Ruby 教程说它应该是4. Larry.whee显然应该返回6

顺便说一句,我添加了 " wheel" 和 " whee" 函数,以便我可以看到值。谁能解释这里有什么问题?

4

2 回答 2

1

Ruby 中的类变量既奇怪令人困惑

实现您想要的一种惯用方法是:

class Car
  def wheels
    4
  end
end

class StretchLimo < Car
  def wheels
    6
  end
end

Car.new.wheels #=> 4
StretchLimo.new.wheels #=> 6

发生的事情是类变量在类的所有实例之间共享。因为StrechLimoCar实例的子类StrechLimo也看到了这个变量。

于 2012-09-05T18:49:53.267 回答
0

@@是一个类变量,因此它在从给定类和所有派生类实例化的所有对象之间共享。因为 Ruby 是解释型的,所以在您实例化一个StretchLimo对象之前,它不应该查看任何StretchLimo代码,所以如果您执行以下操作:

moe = Car.new
moe.wheel # should give 4
larry = StretchLimo.new
moe.wheel # should give 6

因为当StretchLimo被解释时,它会将@@wheels类变量更新为6. 另一方面,如果您声明“轮子”只有一个“ @” ( @wheels),它将是特定于对象本身的实例变量,您将获得您喜欢的行为。

于 2012-09-05T18:38:56.443 回答