为什么@@ class_variables在Ruby中避免?
-
05-10-2019 - |
题
我知道有人说班级变量(例如 @@class_var
)应避免在Ruby中,并应使用实例变量(例如 @instance_var
)在课堂范围中:
def MyClass
@@foo = 'bar' # Should not do this.
@foo = 'bar' # Should do this.
end
为什么在红宝石中皱眉的类变量的使用?
解决方案
班级变量通常是因为它们有时在继承方面令人困惑的行为而受到恶意:
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
这通常更有用。
其他提示
当心;班级 @@variables
和实例 @variables
不是同一件事。
本质上,当您在基类中声明类变量时,它将与所有子类共享。在子类中更改其价值将影响基类及其所有子类一直沿继承树。这种行为通常正是所需的。但同样,这种行为通常不是程序员的意图,并且会导致错误,尤其是如果程序员最初不希望该类被其他人群体分类。
从: http://sporkmonger.com/2007/2/2/19/instance-variables-class-variables-and-inheritance-in-in-ruby
不隶属于 StackOverflow