Ruby类:initialize self与@variable

前端之家收集整理的这篇文章主要介绍了Ruby类:initialize self与@variable前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以解释在定义类时初始化“self”和使用@variables之间的区别吗?

这是一个例子

  1. class Child < Parent
  2. def initialize(self,stuff):
  3. self.stuff = stuff
  4. super()
  5. end
  6. end

那么在这种情况下,我不能用@stuff替换self.stuff?有什么不同?另外,super()只是意味着父应该继承它的父初始化方法是什么?

解决方法

一般来说,不,self.stuff = stuff和@stuff =的东西是不同的.前者在对象上进行一个方法调用stuff =,而后者直接设置一个实例变量.前者调用一个可能是public的方法(除非在类中特别声明为private),而后者则始终设置私有实例变量.

通常,它们看起来一样,因为在类上定义attr_accessor:stuff是很常见的. attr_accessor大致相当于以下内容

  1. def stuff
  2. @stuff
  3. end
  4.  
  5. def stuff=(s)
  6. @stuff = s
  7. end

所以在这种情况下,它们在功能上是一样的.然而,可以定义公共接口以允许不同的结果和副作用,这将使这两个“分配”明显不同:

  1. def stuff
  2. @stuff_called += 1 # Keeps track of how often this is called,a side effect
  3. return @stuff
  4. end
  5.  
  6. def stuff=(s)
  7. if s.nil? # Validation,or other side effect. This is not triggered when setting the instance variable directly
  8. raise "Argument should not be nil"
  9. end
  10. @stuff = s
  11. end

猜你在找的Ruby相关文章