Ruby 类:初始化 self 与 @variable [英] Ruby classes: initialize self vs. @variable
问题描述
有人可以解释在定义类时初始化self"和使用@variables 之间的区别吗?
Can someone explain the difference between initializing "self" and having @variables when defining classes?
这是一个例子
class Child < Parent
def initialize(self, stuff):
self.stuff = stuff
super()
end
end
那么在这种情况下,我不能用 @stuff
替换 self.stuff
吗?有什么不同?另外,super()
只是意味着 Parent 初始化方法中的任何内容,Child 都应该继承它,对吗?
So in this case, wouldn't I be able to replace self.stuff
with @stuff
? What's the difference? Also, the super()
just means whatever is in the Parent initialize method the Child should just inherit it right?
推荐答案
一般来说,不,self.stuff = stuff
和 @stuff = stuff
是不同的.前者在对象上对 stuff=
进行方法调用,而后者直接设置实例变量.前者调用一个可能是公共的方法(除非在类中明确声明为私有),而后者总是设置一个私有实例变量.
In general, no, self.stuff = stuff
and @stuff = stuff
are different. The former makes a method call to stuff=
on the object, whereas the latter directly sets an instance variable. The former invokes a method which may be public (unless specifically declared private in the class), whereas the latter is always setting a private instance variable.
通常,它们看起来相同,因为在类上定义 attr_accessor :stuff
是很常见的.attr_accessor
大致相当于以下内容:
Usually, they look the same because it is common to define attr_accessor :stuff
on classes. attr_accessor
is roughly equivalent to the following:
def stuff
@stuff
end
def stuff=(s)
@stuff = s
end
所以在这种情况下,它们在功能上是相同的.但是,可以定义公共接口以允许不同的结果和副作用,这将使这两个分配"明显不同:
So in that case, they are functionally identical. However, it is possible to define the public interface to allow for different results and side-effects, which would make those two "assignments" clearly different:
def stuff
@stuff_called += 1 # Keeps track of how often this is called, a side effect
return @stuff
end
def stuff=(s)
if s.nil? # Validation, or other side effect. This is not triggered when setting the instance variable directly
raise "Argument should not be nil"
end
@stuff = s
end
这篇关于Ruby 类:初始化 self 与 @variable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!