gpt4 book ai didi

Ruby 类实例变量与类变量

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

我读了https://stackoverflow.com/questions/826734/when-do-ruby-instance-variables-get-set但我对何时使用类实例变量有两种看法。

类变量由一个类的所有对象共享,实例变量属于一个对象。如果我们有类变量,就没有多少空间可以使用类实例变量了。

谁能解释一下这两者之间的区别以及何时使用它们?

这是一个代码示例:

class S
@@k = 23
@s = 15
def self.s
@s
end
def self.k
@@k
end

end
p S.s #15
p S.k #23

更新:我现在明白了!类实例变量不沿继承链传递。

最佳答案

类的实例变量:

class Parent
@things = []
def self.things
@things
end
def things
self.class.things
end
end

class Child < Parent
@things = []
end

Parent.things << :car
Child.things << :doll
mom = Parent.new
dad = Parent.new

p Parent.things #=> [:car]
p Child.things #=> [:doll]
p mom.things #=> [:car]
p dad.things #=> [:car]

类变量:

class Parent
@@things = []
def self.things
@@things
end
def things
@@things
end
end

class Child < Parent
end

Parent.things << :car
Child.things << :doll

p Parent.things #=> [:car,:doll]
p Child.things #=> [:car,:doll]

mom = Parent.new
dad = Parent.new
son1 = Child.new
son2 = Child.new
daughter = Child.new

[ mom, dad, son1, son2, daughter ].each{ |person| p person.things }
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]

使用类上的实例变量(而不是该类的实例),您可以存储该类共有的内容,而无需子类自动获取它们(反之亦然)。使用类变量,您可以方便地不必从实例对象编写 self.class,并且(如果需要)您还可以在整个类层次结构中自动共享。


将这些合并到一个示例中,该示例还涵盖了实例上的实例变量:

class Parent
@@family_things = [] # Shared between class and subclasses
@shared_things = [] # Specific to this class

def self.family_things
@@family_things
end
def self.shared_things
@shared_things
end

attr_accessor :my_things
def initialize
@my_things = [] # Just for me
end
def family_things
self.class.family_things
end
def shared_things
self.class.shared_things
end
end

class Child < Parent
@shared_things = []
end

然后在行动:

mama = Parent.new
papa = Parent.new
joey = Child.new
suzy = Child.new

Parent.family_things << :house
papa.family_things << :vacuum
mama.shared_things << :car
papa.shared_things << :blender
papa.my_things << :quadcopter
joey.my_things << :bike
suzy.my_things << :doll
joey.shared_things << :puzzle
suzy.shared_things << :blocks

p Parent.family_things #=> [:house, :vacuum]
p Child.family_things #=> [:house, :vacuum]
p papa.family_things #=> [:house, :vacuum]
p mama.family_things #=> [:house, :vacuum]
p joey.family_things #=> [:house, :vacuum]
p suzy.family_things #=> [:house, :vacuum]

p Parent.shared_things #=> [:car, :blender]
p papa.shared_things #=> [:car, :blender]
p mama.shared_things #=> [:car, :blender]
p Child.shared_things #=> [:puzzle, :blocks]
p joey.shared_things #=> [:puzzle, :blocks]
p suzy.shared_things #=> [:puzzle, :blocks]

p papa.my_things #=> [:quadcopter]
p mama.my_things #=> []
p joey.my_things #=> [:bike]
p suzy.my_things #=> [:doll]

关于Ruby 类实例变量与类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15773552/

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