现在的位置: 首页 > 综合 > 正文

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

2018年04月18日 ⁄ 综合 ⁄ 共 1325字 ⁄ 字号 评论关闭

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

    博客分类:

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

Ruby代码 复制代码
收藏代码
  1. class IntelligentLife   
  2.   @@home_planet = nil 
  3.    
  4.   def self.home_planet 
  5.     @@home_planet 
  6.   end 
  7.   def self.home_planet=(x) 
  8.     @@home_planet = x 
  9.   end 
  10.   #... 
  11. end 
  12. class Terran < IntelligentLife 
  13.   @@home_planet = "Earth" 
  14. end 
  15.  
  16. class Martian < IntelligentLife 
  17.   @@home_planet = "Mars" 
  18. end 
  19.  
  20.  
  21. p IntelligentLife.home_planet 
  22. p Terran.home_planet 
  23. p Martian.home_planet 

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

在这里我们如果想要得到我们所需要的结果,我们就要使用类实例变量,因为类实例变量是严格的per-class。而不是被整个继承体系所共享。

Java代码 复制代码
收藏代码
  1. class IntelligentLife   
  2.   @home_planet = nil 
  3.    
  4. class << self 
  5.     attr_accessor :home_planet 
  6.   end 
  7. end 
  8. class Terran < IntelligentLife 
  9.   @home_planet = "Earth" 
  10. end 
  11.  
  12. class Martian < IntelligentLife 
  13.   @home_planet = "Mars" 
  14. end 
  15.  
  16.  
  17. p IntelligentLife.home_planet 
  18. p Terran.home_planet 
  19. p Martian.home_planet 

抱歉!评论已关闭.