下面的代码按预期运行,但是它们是否有任何缺点用属性的 getter 覆盖方法(参见下面代码中的 action_label)?查看代码中的:action_label
class BaseAction
def action_label
raise NotImplementedError
end
def run
puts "Running action: #{action_label}"
yield
end
end
class SimpleAction < BaseAction
def initialize(label)
@action_label = label
end
private
attr_reader :action_label
end
sa = SimpleAction.new("foo")
sa.run {puts "action!"}
最佳答案
attr_reader :action_label
只是定义了一个方法。 Ruby 中的“getter”就是这样的方法
def action_label
@action_label
end
attr_reader
是定义此类方法的简写。
在子类中重新定义一个方法没有错,这是 OOP 的一大特点。
那也不是NotImplementedError是为了。提高其他东西。
关于ruby - 在 Ruby 中使用 getter 覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52335096/