gpt4 book ai didi

ruby - ruby 中的子类可以访问实例变量吗?

转载 作者:数据小太阳 更新时间:2023-10-29 08:19:41 25 4
gpt4 key购买 nike

我最近开始学习 ruby​​ 。我想知道 ruby​​ 中的实例变量到底是什么。我写了一段小代码来了解什么是实例变量。

class Animal
def animal_sound
@sound = "roar"
@sound + " "+"animal"
end
end
class Human < Animal
def human_sound
@sound + " "+"human"
end
end
human = Human.new
p human.animal_sound
p human.human_sound

输出:

"roar animal"
"roar human"

我知道实例变量只属于一个类,它的子类是分开的。但是我的人类类如何能够从动物类访问@sound?

最佳答案

how did my human class was able to access @sound from animal class?

它没有。它访问了继承的方法 (Animal#animal_sound)。当您执行 human.animal_sound 时,它将 @sound 附加到当前 self,即 human -- 实例(不是 Human,也不是 Animal)。 @sound 不属于类;它属于实例(这就是它被称为实例变量的原因)。然后,human.human_sound 再次从当前的 self 中读取 @sound,即 human(不是从 人类,而不是动物)。

关于ruby - ruby 中的子类可以访问实例变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39887198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com