继承期间的类方法行为

时间:2009-11-17 23:58:28

标签: ruby

class A
  #define class level attribute called key
  class << self
    attr_accessor :key
  end
end

class B < A
end

B.key = "foo"
B.key # returns "foo"
A.key # returns nil

如果我希望A.key在上述场景中返回“foo”,该怎么办?

2 个答案:

答案 0 :(得分:1)

我知道的唯一方法是手动声明类函数。子类将返回父级的值,但不能让它们返回不同的值。

class A
  def self.key
    @@key
  end

  def self.key=(new_val)
    @@key = new_val
  end
end

答案 1 :(得分:0)

类方法不能是虚拟的。这就是生活。当你有一个类时,你没有虚拟表。

相关问题