直接访问实例变量与使用访问器方法 [英] Directly accessing an instance variable vs. Using an accessor method

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

问题描述

谁能解释通过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屋!

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