Ruby 继承期间的类方法行为 A类 #定义名为key的类级属性 类
类方法不能是虚拟的。这就是生活。当您有一个类时,就没有虚拟表。我知道的唯一方法是手动声明类函数。子类将返回父类的值,但不能让它们返回其他值Ruby 继承期间的类方法行为 A类 #定义名为key的类级属性 类,ruby,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 n
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
class A
def self.key
@@key
end
def self.key=(new_val)
@@key = new_val
end
end