从子类访问实例变量 [英] Access an instance variable from child classes

查看:55
本文介绍了从子类访问实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从子类访问父类的数据成员.我不知道如何称呼它.我发现了很多关于访问类变量的信息,但没有找到来自子类的实例变量.这是我的代码:

I'm trying to access a datamember of a parent class from a child class. I am not sure how to call it. I have found a lot of info about accessing class variables but not instance variables from a child class. Here is my code:

class Shape

    @var = "woohoo"

    def initialize ()

    end

    def area ()

    end

end


class Rectangle < Shape

    @length
    @width

    def initialize ( l,w )
        @length = l
        @width = w
    end

    def area ()
      print @var
      return @length * @width
    end

end

我在尝试打印 @var 时出错.我尝试了 parent.@var、Shape.@var 以及我期望从其他语言获得的许多其他组合.在子类的实例中打印(并在可能的情况下更改)该变量的正确方法是什么?

I get an error trying to print @var. I tried parent.@var, Shape.@var, and a number of other combinations that I'd expect from other languages. What is the correct way to print (and if possible change) that variable within an instance of the child class?

我希望子类的各个实例用它们自己独特的字符串替换woohoo"字符串.

I want individual instances of the child class to replace the 'woohoo' string with their own unique strings.

谢谢!

推荐答案

您可以使用super"来调用父类初始化块并定义实例变量@var".在这种情况下,您可以为另一个实例修改此实例变量的值.像这样:

You can use "super" to call parent class initialize block and define instance variable "@var". In that case you can modify value of this instance variable for another instance. Like this:

class Shape
  def initialize ()
    @var = "woohoo"
  end
end

class Rectangle < Shape
  def initialize(l, w)
    @length = l
    @width = w
    super()
  end

  def area()
    print @var
    return @length * @width
  end

  def var=(new_value)
    @var = new_value
  end
end

a = Rectangle.new(1,1)
a.area
# => woohoo1
a.var = "kaboom"
a.area
# => kaboom1

b = Rectangle.new(2,2)
b.area
# => woohoo4

或者 ofc 你可以使用 attr_accessor

Or ofc you can use attr_accessor

class Shape
  def initialize
    @var = "woohoo"
  end
end

class Rectangle < Shape

  attr_accessor :var
  def initialize(l, w)
    @length, @width = l, w
    super()
  end

  def area()
    print @var
    return @length * @width
  end
end

a = Rectangle.new(1,1)
a.area
# => woohoo1
a.var = "kaboom"
a.area
# => kaboom1

b = Rectangle.new(2,2)
b.area
# => woohoo4

这篇关于从子类访问实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆