gpt4 book ai didi

Ruby 继承和重写类方法

转载 作者:数据小太阳 更新时间:2023-10-29 08:31:12 25 4
gpt4 key购买 nike

我设置了两个类,如下所示

class Parent

def self.inherited(child)
child.custom_class_method
end

def self.custom_class_method
raise "You haven't implemented me yet!"
end
end

class Child < Parent

def self.custom_class_method
"hello world"
end
end

好像继承的时候Child < Parent被评估,它调用self.inherited ,这又引发了 Parent self.custom_class_method 的版本而不是 Child的。这是一个问题,因为没有得到预期的 "hello world"。我收到一条错误提示 "You haven't implemented me yet!"

是否 Childself.custom_class_method直到 Parent 之后才进行评估的 self.inherited评价完了吗?如果是这样,也许有解决办法吗?我不应该放 raise 吗?检查父类?

最佳答案

我认为这应该澄清:

class Parent
def self.inherited(child)
puts "Inherited"
end
end

class Child < Parent
puts "Starting to define methods"
def self.stuff; end
end

输出清楚地表明 .inherited 在您打开新类时被调用,而不是在您关闭它时被调用。因此,正如您所猜测的那样,Child.custom_class_method 在您尝试调用它时并不存在 - 所有 .inherited 看到的都是一张白纸。

(至于如何绕过它......不幸的是,如果没有更深入地了解你正在尝试做的事情,我不能说。)

关于Ruby 继承和重写类方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33092454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com