直接访问实例变量与使用访问器方法 [英] Directly accessing an instance variable vs. Using an accessor method
问题描述
谁能解释通过self.attribute
和@attribute
访问实例属性之间的区别?
Can anyone explain the difference between accessing an instance attribute via self.attribute
and by @attribute
?
推荐答案
self.attribute
调用方法attribute
.
self.attribute = value
使用参数value
调用方法attribute=
.
@attribute
和@attribute = value
获取/设置实例变量@attribute
的值.
self.attribute
calls the method attribute
.
self.attribute = value
calls the method attribute=
with the argument value
.
@attribute
and @attribute = value
get/set the value of the instance variable @attribute
.
所以基本上它们是两个完全不同的东西.
So basically they're two entirely different things.
但是,如果调用attr_accessor :attribute
,它将定义方法attribute
返回@attribute
,并定义方法attribute=(value)
设置@attribute = value
.因此,在这种情况下,没有区别.
However if you call attr_accessor :attribute
it defines the method attribute
to return @attribute
and the method attribute=(value)
to set @attribute = value
. So in that case, there is no difference.
这篇关于直接访问实例变量与使用访问器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!