Ruby与继承
我试图理解继承:Ruby与继承,ruby,class,inheritance,Ruby,Class,Inheritance,我试图理解继承: 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.wheel,我得到6,当我期待4 我下面的Ruby教程说它应该是4Larry.whee显然应该返回6 顺便说一下,我添加了“whe
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.wheel
,我得到6
,当我期待4
我下面的Ruby教程说它应该是4
Larry.whee
显然应该返回6
顺便说一下,我添加了“
wheel
”和“whee
”函数,以便查看值。谁能解释一下这里的错误吗?@
是一个类变量,因此它在从给定类和所有派生类实例化的所有对象之间共享。因为Ruby是解释的,所以在实例化StretchLimo
对象之前,它不应该查看任何StretchLimo
代码,因此如果您执行以下操作:
moe = Car.new
moe.wheel # should give 4
larry = StretchLimo.new
moe.wheel # should give 6
因为当对
StretchLimo
进行解释时,它会将
类变量更新为6
。另一方面,如果您仅用一个“@
”(@wheels
)声明了“wheels”,那么它将是特定于对象本身的实例变量,您将获得首选行为。Ruby中的类变量是和
实现所需功能的惯用方法如下:
class Car
def wheels
4
end
end
class StretchLimo < Car
def wheels
6
end
end
Car.new.wheels #=> 4
StretchLimo.new.wheels #=> 6
等级车
def车轮
4.
结束
结束
级担架车
def车轮
6.
结束
结束
汽车.新.车轮#=>4
StretchLimo.new.wheels#=>6
发生的是类变量在类的所有实例之间共享。因为
StrechLimo
是Car
的子类,StrechLimo
的实例也可以看到这个变量。欢迎使用stackoverflow。请正确格式化您的代码。ruby中的类变量很奇怪,令人困惑。不使用它们可能是最容易的。事实并非如此<代码>移动轮在第二行给出6。试试看。这取决于目录结构和解释方式。如果两个类都在同一个文件中定义并从中加载,我会得到moe.wheel->6,但如果我强制解释器按顺序加载这些类,情况就不是这样了。无论如何,首选方法是使用实例变量这几乎肯定不是首选方法…请参阅
class Car
def wheels
4
end
end
class StretchLimo < Car
def wheels
6
end
end
Car.new.wheels #=> 4
StretchLimo.new.wheels #=> 6