Ruby中的继承和实例变量

Mes*_*ssi 1 ruby

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

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
Run Code Online (Sandbox Code Playgroud)

这输出:

2
3
Run Code Online (Sandbox Code Playgroud)

在这里,类B从类继承A,并@x在课堂上B没有任何与继承.

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

" Ruby继承 "页面说:

由于实例变量与继承无关,因此子类使用的实例变量不能"遮蔽"超类中的实例变量.如果子类使用与其祖先之一使用的变量同名的实例变量,则它将覆盖其祖先变量的值.

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

und*_*gor 7

B继承initializeA.

在对象创建时,initialize调用.所以你甚至可以@x设置为2类的对象B.

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

class A
  def initialize
    @x = 42
  end
end

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

h = B.new
Run Code Online (Sandbox Code Playgroud)

现在,h只有一个@x具有值的实例变量23.它不像有一个@x来自B一个A.你可以在这里看到:

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
Run Code Online (Sandbox Code Playgroud)