从类外部访问实例变量 [英] Access instance variable from outside the class
问题描述
如果实例变量属于一个类,是否可以使用类实例直接访问该实例变量(例如@hello
)?
If an instance variable belongs to a class, can I access the instance variable (e.g. @hello
) directly using the class instance?
class Hello
def method1
@hello = "pavan"
end
end
h = Hello.new
puts h.method1
推荐答案
是的,您可以像这样使用instance_variable_get
:
Yes, you can use instance_variable_get
like this:
class Hello
def method1
@hello = "pavan"
end
end
h = Hello.new
p h.instance_variable_get(:@hello) #nil
p h.method1 #"pavan" - initialization of @hello
p h.instance_variable_get(:@hello) #"pavan"
如果变量未定义(在我的示例中为第一次调用instance_variable_get
),则会得到nil
.
If the variable is undefined (first call of instance_variable_get
in my example) you get nil
.
如安德鲁(Andrew)在其评论中所述:
As Andrew mention in his comment:
您不应将此方法作为访问实例变量的默认方式,因为它违反了封装.
You should not make this the default way you access instance variables as it violates encapsulation.
更好的方法是定义访问器:
A better way is to define an accessor:
class Hello
def method1
@hello = "pavan"
end
attr_reader :hello
end
h = Hello.new
p h.hello #nil
p h.method1 #"pavan" - initialization of @hello
p h.hello #"pavan"
如果要使用其他方法名称,则可以别名访问器:alias :my_hello :hello
.
If you want another method name, you could alias the accessor: alias :my_hello :hello
.
如果该类不是在代码中定义的,而是在gem中定义的:您可以向类中插入新功能.
And if the class is not defined in your code, but in a gem: You can modify classes in your code and insert new functions to classes.
这篇关于从类外部访问实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!