gpt4 book ai didi

Ruby 类继承 : How to preven a public method from beeing overwritten in the child classes

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

是否可以防止公共(public)方法在子类中被覆盖?

class Parent
def some_method
#important stuff that should never be overwritten
end
end

class Child < Parent
def some_method
#should not be possible to overwrite (raise an error if a child class tries to do it)
end
end

谢谢!

最佳答案

您可以为此目的使用“method_added”和“inherited” Hook :

class Foo
def self.inherited(sub)
sub.class_eval do
def self.method_added(name)
if name == :some_method
remove_method name
raise Exception, "Can't override #{name} method"
end
end
end
end
end

class Bar < Foo
end

class Bar
def some_method
end
end
# => Exception: Can't override some_method method

关于Ruby 类继承 : How to preven a public method from beeing overwritten in the child classes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7834760/

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