加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么要在Ruby中避免使用@@ class_variables?

发布时间:2020-12-16 20:33:11 所属栏目:百科 来源:网络整理
导读:我知道有些人说Ruby中应该避免使用类变量(例如@@ class_var),而应该在类范围内使用一个实例变量(例如@instance_var): def MyClass @@foo = 'bar' # Should not do this. @foo = 'bar' # Should do this.end 为什么在Ruby中使用类变量? 解决方法 类变量常常
我知道有些人说Ruby中应该避免使用类变量(例如@@ class_var),而应该在类范围内使用一个实例变量(例如@instance_var):
def MyClass
  @@foo = 'bar' # Should not do this.
  @foo = 'bar'  # Should do this.
end

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

解决方法

类变量常常因为继承而混淆的行为而被篡改:
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

这通常更有用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读