14

我知道有人说@@class_var在 Ruby 中应该避免使用类变量(例如),而应该@instance_var在类范围内使用实例变量(例如):

def MyClass
  @@foo = 'bar' # Should not do this.
  @foo = 'bar'  # Should do this.
end

为什么在 Ruby 中不赞成使用类变量?

4

2 回答 2

27

类变量经常被诟病,因为它们在继承方面有时会出现令人困惑的行为:

class Foo
  @@foo = 42

  def self.foo
    @@foo
  end
end

class Bar < Foo
  @@foo = 23
end

Foo.foo #=> 23
Bar.foo #=> 23

如果您改用类实例变量,您将获得:

class Foo
  @foo = 42

  def self.foo
    @foo
  end
end

class Bar < Foo
  @foo = 23
end

Foo.foo #=> 42
Bar.foo #=> 23

这通常更有用。

于 2010-09-24T13:05:42.617 回答
6

当心; 类@@variables和实例@variables不是一回事。

本质上,当您在基类中声明类变量时,它与所有子类共享。在子类中更改其值将影响基类及其所有子类,一直沿继承树向下。这种行为通常正是我们所期望的。但同样经常的是,这种行为不是程序员的本意,它会导致错误,尤其是如果程序员最初并不期望该类会被其他人子类化。

来自:http ://sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby

于 2010-09-24T13:07:52.240 回答