ruby中的类变量与类实例变量 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

首先,在ruby1.8中类变量是所有子类和父类共享的,可以看下面的代码:

class IntelligentLife
 @@home_planet = nil

 def  self.home_planet
  @@home_planet
 end
 def self.home_planet=(x)
   @@home_planet = x
 end
 #... 
end
class Terran < IntelligentLife
 @@home_planet = "Earth"
end

class Martian < IntelligentLife
  @@home_planet = "Mars"
end

p IntelligentLife.home_planet
p  Terran.home_planet
p Martian.home_planet

可以看到结果是相同的,都是"Mars".这是因为父类的类变量是被整个继承体系所共享的.

在这里我们如果想要得到我们所需要的结果,我们就要使用类实例变量,因为类实例变量是严格的 per-class,

ruby中的类变量与类实例变量

。而不是被整个继承体系所共享。

class IntelligentLife
 @home_planet = nil

 class << self
  attr_accessor :home_planet
 end
end
class Terran < IntelligentLife
 @home_planet = "Earth"
end

class Martian < IntelligentLife
  @home_planet = "Mars"
end

p IntelligentLife.home_planet
p  Terran.home_planet
p Martian.home_planet

而在1.9中,类变量不再被继承体系所共享,

电脑资料

ruby中的类变量与类实例变量》(https://www.unjs.com)。也就是和java中的静态变量差不多了。

下面的代码在1.9中运行.

class IntelligentLife
 @@home_planet = "bobo"
 def self.home_planet
  @@home_planet
 end
end
class Terran < IntelligentLife
 @@home_planet  = "Earth"
end

class Martian < IntelligentLife
 @@home_planet =  "Mars"
 def self.home_planet
  @@home_planet
 end
end

p  IntelligentLife.home_planet
p Terran.home_planet
p Martian.home_planet

可以看到这时的类变量才是真正的类变量,也就是说是per-class的了.

最新文章