【问题标题】:In Ruby, why do you need to initialize child class variables?在 Ruby 中,为什么需要初始化子类变量?
【发布时间】:2013-09-02 18:57:52
【问题描述】:

我有一个类 Foo,我创建了一个子案例 Bar。 @foo_count 已经在父类中初始化了,为什么还要在子类中初始化呢?

请指教?

class Foo
  @foo_count = 0  
end

class Bar < Foo
  @foo_count = 100
end

【问题讨论】:

    标签: ruby class variables


    【解决方案1】:

    为什么会这样?好吧,让我这样告诉你:

    class Foo
      @foo_count = 0  
    end
    
    class Bar < Foo;end
    
    Bar.instance_variables # => []
    Foo.instance_variables # => [:@foo_count]
    

    @foo_countFoo类实例变量。每当您要从像Foo 这样的超类创建像Bar 这样的子类时,不要认为类实例变量会被继承到类Bar。现在看看 -

    class Foo
      @foo_count = 0  
    end
    
    class Bar < Foo
      @foo_count = 10
    end
    
    Bar.instance_variables # => [:@foo_count]
    Foo.instance_variables # => [:@foo_count]
    

    现在FooBar 对象都有它们的实例变量,只有同名@foo_count,这并不意味着它们共享同一个实例变量。每个对象总是有自己的实例副本变量。

    这里有更多的例子可以让你清楚:-

    class Foo
      @foo_count = 0 
      def self.meth_foo 
        @foo_count
      end 
    end
    
    class Bar < Foo
      #@foo_count = 10
    end
    
    Foo.meth_foo # => 0
    Bar.meth_foo # => nil
    

    但是现在——

    class Foo
      @foo_count = 0 
      def self.meth_foo 
        @foo_count
      end 
    end
    
    class Bar < Foo
      @foo_count = 10
    end
    
    Foo.meth_foo # => 0
    Bar.meth_foo # => 10
    

    【讨论】:

      【解决方案2】:

      实例变量在它们被创建时将它们自己附加到任何对象本身。 Foo 中的实例变量@foo_count 附加到Foo 类对象,因此它被称为类实例变量。同样,Bar 中的实例变量@foo_count 将自身附加到 Bar 类对象。结果,有两个类实例变量——不是一个。对象不共享实例变量——每个对象都有自己的实例变量。

      class Foo
        puts self
      
        @foo_count = 0  
      end
      
      class Bar < Foo
        puts self
      
        @foo_count = 100
      end
      
      --output:--
      Foo
      Bar
      

      顺便说一句,如果你想继承变量你可以使用类变量

      class Foo
        @@foo_count = 'hello' 
      end
      
      class Bar < Foo
        def greet
          puts @@foo_count
        end
      
      end
      
      Bar.new.greet
      
      --output:--
      hello
      

      但是,许多人认为使用类变量是不好的做法。它们不像其他语言中的类变量,因此会产生意想不到的后果,因此人们通常坚持类实例变量

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-11
        • 1970-01-01
        • 2015-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-01
        相关资源
        最近更新 更多