一些代碼從孩子
class Parent
def print
p "Hi I'm the parent"
end
end
class Child < Parent
def initialize(num)
@num = num
end
def print
child_print
end
def child_print
if @num == 1
#call parent.print
else
p "I'm the child"
end
end
end
c1 = Child.new(1)
c2 = Child.new(2)
c1.print
c2.print
Child
調用父母的方法是Parent
一個實例。 Print
是接口中暴露的方法,並且這兩個類都定義了它們。 Child
決定在一個(可能非常複雜的)方法中做其他事情,但會在某些條件下調用其父方法。
我可以只寫
def print
if @num == 1
super
else
p "I'm the child"
end
end
而且這樣的作品,但如果它不只是一個簡單的一行比較,而是在做很多值得被分離成另一種方法,複雜的東西?在決定應該調用父母的方法之前,可能需要做一些計算。
或者也許有不同的更好的方式來設計它。
我不明白這裏的問題。您仍然可以通過非常複雜的方法調用「超級」(即使在不同的分支甚至多次)。 – Koraktor
'child_print'應該調用Parent的'print'。我認爲super只是在超類中調用同名的方法。或者,我可能不知道如何正確使用'super'。甚至有一個'child_print'的原因是因爲我不想讓與它無關的東西膨脹到print方法,但仍然需要確定是調用孩子的打印還是父母的打印。 – MxyL
啊,對不起。這裏已經很晚了。 ;)一會兒。 – Koraktor