类变量和类实例变量之间的区别? [英] Difference between class variables and class instance variables?

查看:174
本文介绍了类变量和类实例变量之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我有关类变量和类实例变量之间的区别吗?

Can anyone tell me about the difference between class variables and class instance variables?

推荐答案

该类及其所有后代之间共享一个类变量(@@).类的后代不共享类实例变量(@).

A class variable (@@) is shared among the class and all of its descendants. A class instance variable (@) is not shared by the class's descendants.

类变量(@@)

Class variable (@@)

我们有一个带有类变量@@i的Foo类,以及用于读写@@i的访问器:

Let's have a class Foo with a class variable @@i, and accessors for reading and writing @@i:

class Foo

  @@i = 1

  def self.i
    @@i
  end

  def self.i=(value)
    @@i = value
  end

end

还有一个派生类:

class Bar < Foo
end

我们看到Foo和Bar的@@i值相同:

We see that Foo and Bar have the same value for @@i:

p Foo.i    # => 1
p Bar.i    # => 1

同时更改一个@@i会同时更改两者:

And changing @@i in one changes it in both:

Bar.i = 2
p Foo.i    # => 2
p Bar.i    # => 2


类实例变量(@)


Class instance variable (@)

让我们创建一个具有类实例变量@i和用于读取和写入@i的访问器的简单类:

Let's make a simple class with a class instance variable @i and accessors for reading and writing @i:

class Foo

  @i = 1

  def self.i
    @i
  end

  def self.i=(value)
    @i = value
  end

end

还有一个派生类:

class Bar < Foo
end

我们看到,尽管Bar继承了@i的访问器,但它并不继承@i本身:

We see that although Bar inherits the accessors for @i, it does not inherit @i itself:

p Foo.i    # => 1
p Bar.i    # => nil

我们可以在不影响Foo的@i的情况下设置Bar的@i:

We can set Bar's @i without affecting Foo's @i:

Bar.i = 2
p Foo.i    # => 1
p Bar.i    # => 2

这篇关于类变量和类实例变量之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆