gpt4 book ai didi

Ruby 类 : initialize self vs. @variable

转载 作者:数据小太阳 更新时间:2023-10-29 06:37:15 24 4
gpt4 key购买 nike

有人可以解释在定义类时初始化“self”和使用@variables 之间的区别吗?

举个例子

class Child < Parent
def initialize(self, stuff):
self.stuff = stuff
super()
end
end

所以在这种情况下,我不能用 @stuff 替换 self.stuff 吗?有什么不同?此外,super() 只是意味着 Parent 初始化方法中的任何内容,Child 应该直接继承它,对吗?

最佳答案

一般来说,不是,self.stuff = stuff@stuff = stuff 是不一样的。前者在对象上调用stuff=方法,后者直接设置实例变量。前者调用一个可能是公共(public)的方法(除非在类中特别声明为私有(private)),而后者总是设置一个私有(private)实例变量。

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

def stuff
@stuff
end

def stuff=(s)
@stuff = s
end

所以在那种情况下,它们在功能上是相同的。但是,可以定义公共(public)接口(interface)以允许不同的结果和副作用,这将使这两个“任务”明显不同:

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 类 : initialize self vs. @variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12097726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com