【问题标题】:Confused by Ruby's class constructors and virtual accessors对 Ruby 的类构造函数和虚拟访问器感到困惑
【发布时间】:2014-04-14 07:36:23
【问题描述】:

作为一个以前只接触过有限的编程并且主要是 Python 和 C++ 的人,我发现 Ruby 是一种非常令人耳目一新且令人愉快的语言,但是我在理解 Ruby 对类构造函数和虚拟访问器的使用方面有点困难,特别是什么是构造函数,什么不被认为是构造函数,以及我是否正确理解了虚拟访问器。

这是一个示例(归功于 Pragmatic Bookshelf, Programming Ruby 1.9 & 2.0):

class BookInStock
  attr_accessor :isbn, :price # is this part of the class constructor?

  def initialize(isbn, price) # and is the initialize method part of a constructor or just a regular method?
    @isbn = isbn 
    @price = price
  end

  def price_in_cents 
    Integer(price*100+0.5)
  end

  def price_in_cents=(cents) # this is a 'virtual accessor' method, trough which I am able to update the price down the road...?
    @price = cents / 100.0 
  end
end

book = BookInStock.new('isbn1', 23.50)
puts "Price: #{book.price}"
puts "Price in cents: #{book.price_in_cents}"
book.price_in_cents = 1234 # here I am updating the value thanks to the 'virtual accessor' declared earlier, as I understand it
puts "New price: #{book.price}"
puts "New price in cents: #{book.price_in_cents}"

感谢所有帮助我理解这段代码。

【问题讨论】:

标签: ruby oop constructor accessor


【解决方案1】:

1 attr_accessor :isbn, :price # 这部分是类构造函数吗?

这条线是通过仅方法哲学来保持访问私有成员的概念。相当于声明了两个私有成员及其getter和setter方法,与构造函数无关。

2 def initialize(isbn, price) # 初始化方法是构造函数的一部分还是只是常规方法?

简单地说,这是构造函数。该方法被“新”关键字调用

3 def price_in_cents=(cents) # 这是一个“虚拟访问器”方法,通过它我可以在以后更新价格...?

它只是 price= 方法的一种替代方法,它接受不同格式的参数,price= 方法是您的问题行 1 自动生成的 setter 方法。

4 book.price_in_cents = 1234 # 在这里我正在更新值,这要归功于前面声明的“虚拟访问器”,据我所知

请记住,这感觉就像分配一个变量,但实际上是在访问一个 setter 方法,这与您的问题第 1 行和第 3 行中反映的概念一致。

【讨论】:

  • 很有道理,感谢您的精彩解释!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
相关资源
最近更新 更多