ruby 中的实例变量
class Test
def initialize
@var = "125"
end
def testmethod
puts @var
puts "accessing me from child class"
end
end
class TestExtension < Test
def method1
puts @var = "One Hundred and twenty five"
testmethod()
end
end
t = Test.new
p = TestExtension.new
p.method1
t.testmethod
输出:
One Hundred and twenty five
One Hundred and twenty five
accessing me from child class
125
accessing me from child class
我的问题是,访问子类 TestExtension
中的 testmethod()
会导致访问在 @var
中声明的值code>TestExtension 类,而不是访问 Test
类中声明的值。正确吗?
class Test
def initialize
@var = "125"
end
def testmethod
puts @var
puts "accessing me from child class"
end
end
class TestExtension < Test
def method1
puts @var = "One Hundred and twenty five"
testmethod()
end
end
t = Test.new
p = TestExtension.new
p.method1
t.testmethod
output:
One Hundred and twenty five
One Hundred and twenty five
accessing me from child class
125
accessing me from child class
My question is that accessing the testmethod()
in child class TestExtension
results in accessing that value of @var
which is being declared in TestExtension
class instead of accessing the value which is being declared in Test
class . Is it correct ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简短回答:
是的
答案稍长:
顾名思义,实例变量是针对每个实例的。对于每个对象,只能有一个名为
@var
的变量,无论哪个类具有访问它的代码。Short answer:
Yes
Slightly longer answer:
Instance variables are, as their name suggests, per instance. For every object there can only be one variable called
@var
, regardless of which class has the code to access it.这是正确的。
正如 Gareth 所说,实例变量属于实例,而不是类。
如果你希望变量属于类,你可以使用类对象的实例变量(呃,这个术语写起来太复杂了)。
简而言之,Ruby 中的一切都是对象,包括类。在下面的示例中,Base 和 Derivative 只是包含对象引用的常量。这些对象代表类(ta-da!)。
考虑到这一事实,我们可以执行以下操作:
It is correct.
As Gareth said, instance variables belong to instances, not classes.
If you want variables to belong to classes, you may use instance variable of class object (err, this term is to complex to write it correctly).
In short, everything in Ruby is an object, including classes. In the following example Base and Derivative are just constants which contain a reference to objects. Those objects represent classes (ta-da!).
Taking this fact into account, we can do the following: