加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 在object.initialize中,使用self更好.过来@?

发布时间:2020-12-16 19:19:52 所属栏目:百科 来源:网络整理
导读:在可能的情况下,有一个约定可以在其实例变量上引用对象的属性. Practical Object-Oriented Design in Ruby说: Always wrap instance variables in accessor methods instead of directly referring to variables… 这是一个例子,我已经解释过了: class Gea
在可能的情况下,有一个约定可以在其实例变量上引用对象的属性. Practical Object-Oriented Design in Ruby说:

Always wrap instance variables in accessor methods instead of directly
referring to variables…

这是一个例子,我已经解释过了:

class Gear
  attr_reader :chainring,:cog
  ...
  def ratio
    # this is bad
    # @chainring / @cog.to_f
    # this is good
    chainring / cog.to_f
end

我看到使用实例变量创建新对象的最常见方式是:

class Book
  attr_accessor :title
  def initialize(title)
    @title = title
  end
end

@ title =直接访问实例变量title.假设我们遵循’属性超过实例变量’约定,是否更适合使用self.title =,which would tell the object to send itself the message title=,从而使用属性write方法直接对实例变量?

class Book
  attr_accessor :title
  def initialize(title)
    self.title = title
  end
end

本书讨论了“实例变量的属性”,并参考了读取实例变量,但它是否也适用于写作?

解决方法

The book talks about ‘attribute over instance variable’ with reference
to reading an instance variable,but doesn’t it also apply to writing?

是的,它也适用于写作.但是,initialize方法很特殊,因为它负责设置对象.当你使用setter方法时,你这样做是因为setter可能正在做一些额外的工作(例如Rails中的属性设置器).在初始化程序中,您通常不希望产生任何副作用,因此您可以直接访问实例变量.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读