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

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

问题描述

谁能告诉我类变量和类实例变量的区别?

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.

类变量(@@)

让我们有一个带有类变量 @@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

<小时>

类实例变量(@)

让我们用一个类实例变量@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天全站免登陆