【问题标题】:Why should @@class_variables be avoided in Ruby?为什么在 Ruby 中应该避免使用 @@class_variables?
【发布时间】:2011-04-16 18:34:53
【问题描述】:

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

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

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

【问题讨论】:

标签: ruby class-variables class-instance-variables


【解决方案1】:

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

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

这通常更有用。

【讨论】:

    【解决方案2】:

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

    本质上,当你声明一个类时 基类中的变量,它是共享的 与所有子类。改变它 子类中的值会影响 基类及其所有子类 一直到继承树。 这种行为通常正是 想要的。但同样经常,这 行为不是本意 程序员,它会导致错误, 特别是如果程序员没有 最初期望类是 被其他人继承。

    发件人:http://sporkmonger.com/2007/2/19/instance-variables-class-variables-and-inheritance-in-ruby

    【讨论】:

      猜你喜欢
      • 2011-07-10
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 2011-03-10
      • 2018-06-26
      • 1970-01-01
      • 2012-07-15
      • 2014-03-13
      相关资源
      最近更新 更多