如果一个子类继承了父类,它也会继承父类的方法。
那么为什么继承的方法无法访问子类的常量呢?
例如 -
那么为什么继承的方法无法访问子类的常量呢?
例如 -
class Parent
def my_method
puts "Value of FOO is #{FOO}"
end
end
class Child < Parent
FOO = "bar"
end
Child.new.my_method #=> NameError: uninitialized constant Parent::FOO
继承方法不是运行在子类“内部”吗?
我该如何解决这个问题?
my_method
中使用self.class::FOO
而不是FOO
来解决这个问题。 - max pleanerself
? - Cary Swovelandc=Child.new
和c.my_method
,那么在my_method
中self
就是c
。我认为就是这么简单。 - Cary SwovelandParent#my_method
中使用self.class :: FOO
。如果执行c = Child.new
和c.my_method
,则在my_method
内部self
等于c
,因此self.class :: FOO => c.class :: FOO => Child :: FOO =>'bar'
,就像my_method
的所有者是Child
一样。对吗? - Cary Swoveland