zoukankan      html  css  js  c++  java
  • ruby中的类变量与实例变量

    首先,在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  
    
  • 相关阅读:
    leetcode 141. Linked List Cycle
    leetcode 367. Valid Perfect Square
    leetcode150 Evaluate Reverse Polish Notation
    小a与星际探索
    D. Diverse Garland
    C. Nice Garland
    数的划分(动态规划)
    平衡二叉树(笔记)
    1346:【例4-7】亲戚(relation)
    1192:放苹果(dp + 搜索)
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/1517230.html
Copyright © 2011-2022 走看看