[英]How to check whether child method called super or not
class Parent
def a_method
# some crucial work has to run for every child class
end
end
# Example 1
class Child < Parent
def a_method
super
end
end
# Example 2
class Child < Parent
def a_method
end
end
在示例2的情況下,我想引發一個錯誤,即必須在重寫的方法上調用super
我想在示例2的情況下引發錯誤,必須在重寫方法上調用super
這是工作的錯誤工具。 您不能指示孩子該怎么做。 使用某些OO設計最好做到這一點。 如果有些工作必須始終這樣做,那么不建議子類覆蓋方法。 而是僅覆蓋“自定義”部分。 例:
class Parent
def a_method
crucial_work do
custom_handling
end
end
# child classes override this one, not a_method
def custom_handling
# no-op
end
end
class Child < Parent
def custom_handling
"doing custom handling here"
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.