首先,在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,而不是被整个继承体系所共享。
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