Ruby 呼叫家长';孩子的方法
一些代码Ruby 呼叫家长';孩子的方法,ruby,Ruby,一些代码 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
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
这是可行的,但如果它不仅仅是一个简单的一行比较,而是做了很多复杂的事情,应该被分离成另一种方法呢?在决定调用父方法之前,它可能需要进行一些计算
或者也许有一种不同的更好的设计方法
Parent.instance_method(:print).bind(self).call
这已经是相当可读的,但这里有一个解释
父类的#print
方法
#call
提供参数,这些参数将被中继到被调用的方法
PPS:也就是说,这样的代码几乎总是暗示类设计中的问题。你应该尽可能避免它。我不理解这里的问题。您仍然可以使用非常复杂的方法调用
super
(即使在不同的分支中,甚至多次调用)。child\u print
应该调用Parent的print
。我认为super只是在超类中调用同名的方法。或者我不知道如何正确使用super
。甚至还有一个child\u print
的原因是,我不想在print
方法中添加与它无关的内容,但仍然需要确定是调用孩子的print还是家长的print。啊,对不起。这里已经很晚了等一下,我也不喜欢我试图做的事情,但我正在修改其他人的类,他们已经提供了自己的接口和类设计,我一直在尝试使用它。有些情况下,我需要调用父对象的方法,有些情况下,我运行自己的方法。可以用臃肿的方法解决,但我不喜欢大的方法。。
Parent.instance_method(:print).bind(self).call