instance_variable_set/get 与 attr_writer/reader
在某些情况下,我应该在 instance_varaible_set
/instance_variable_get
或 attr_writer
/attr_reader
之间进行选择来访问实例变量物体是从外面来的吗?它们在速度等方面有何不同?
我的印象是,如果您想让最终用户访问实例变量是一个开放的方法,应该使用 attr_writer
/attr_reader
来简化它,但是如果您如果想私下使用它,您宁愿使用 instance_varaible_set
/instance_variable_get
。这种理解正确吗?
Are there any situations where I should chose between instance_varaible_set
/instance_variable_get
or attr_writer
/attr_reader
to access an instance variable of the object from outside of it? How are they different in terms of speed, or etc?
I had the impression that if you want to let accessing the instance variable an opened method to the end user, attr_writer
/attr_reader
should be used to make it easy, but if you want to use it privately, you would rather use instance_varaible_set
/instance_variable_get
. Is this understanding correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是正确的。您可以在类定义中定义
attr_accessor
/attr_reader
/attr_writer
以使它们访问(隐式或显式创建的)实例变量。如果类不是由您编写的并且不存在此类访问器,您仍然可以使用
instance_variable_get
/instance_variable_set
读取/写入私有实例变量。This is correct. You define
attr_accessor
/attr_reader
/attr_writer
inside class definition to make them access (implicitly or explicitly created) instance variable.If class wasn't written by you and no such accessors exist, you still can read/write private instance variables using
instance_variable_get
/instance_variable_set
.