gpt4 book ai didi

ruby - Ruby 中的继承和实例变量

转载 作者:太空宇宙 更新时间:2023-11-03 17:14:43 25 4
gpt4 key购买 nike

我知道实例变量与继承无关:

class A

def initialize
@x = 2
end

end

class B < A

def puts_x
puts @x
end

def x=(value)
@x = value
end

end

b = B.new
b.puts_x
b.x=3
b.puts_x

这个输出:

2
3

这里,B类继承自A类,与B类中的@x无关具有继承性。

但是输出是2。我想了解它。

Ruby Inheritance”页面显示:

Since instance variables have nothing to do with inheritance, it follows that an instance variable used by a subclass cannot "shadow" an instance variable in the super-class. If a subclass uses an instance variable with the same name as a variable used by one of its ancestors, it will overwrite the value of its ancestor's variable.

我也想要这方面的任何例子。

最佳答案

BA 继承了 initialize

在创建对象时,调用initialize。因此,即使对于类 B 的对象,您也将 @x 设置为 2

我认为,你引用的句子是指这种情况:

class A
def initialize
@x = 42
end
end

class B < A
def initialize
@x = 23
end
end

h = B.new

现在,h 只有一个实例变量@x,值为23。它不像 B 中有一个 @xA 中有一个。你可以在这里看到:

class A
def initialize
@x = 42
end

def set_x_from_a
@x = 12
end

def print_x_from_a
puts @x
end
end

class B < A
def initialize
@x = 23
end

def set_x_from_b
@x = 9
end

def print_x_from_b
puts @x
end
end

h = B.new
h.print_x_from_a # => 23
h.print_x_from_b # => 23
h.set_x_from_a
h.print_x_from_b # => 12
h.set_x_from_b
h.print_x_from_a # => 9

关于ruby - Ruby 中的继承和实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35718534/

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