[英]Calling super class' super class method?
How can I get child to ignore what its parent thinks is fun and go straight to the grandparent's idea of fun? 我怎样才能让孩子忽略父母认为有趣的事情,直接去看祖父母的有趣想法?
Child still inherits from the parent, but it just doesn't agree with a couple methods. 子代仍然从父代继承,但是它与几种方法不同。
Calling the method of the super class of the super class? 调用超类的超类的方法?
Also, is it considered poor design if I'm in a situation where the child doesn't agree with its parents but agrees with the parent's parents? 此外,如果我处于孩子不同意父母但同意父母父母的情况下,是否被认为设计不佳?
class Grandparent
def fun
#do stuff
end
end
class Parent < Grandparent
def fun
super
#parent does some stuff
end
def new_business
#unrelated to my parent
end
end
class Child < Parent
def fun
super
#child also does some stuff
end
def inherit_new_business
new_business
#stuff
end
end
It's generally easier in Ruby to get this kind of behavior through composition rather than inheritance. 在Ruby中,通过组合而不是继承通常更容易获得这种行为。 To accomplish that Modules
are included that contain the specific behaviors you wish a class to have. 为了实现这一点,需要包含一些Modules
,这些Modules
包含您希望某个类具有的特定行为。
But if you absolutely have to use inheritance you can do this: 但是,如果您绝对必须使用继承,则可以执行以下操作:
class Child < Parent
def fun
GrandParent.instance_method(:fun).bind(self).call
# fun child stuff
end
end
This will do exactly what it says. 这将完全按照其说的做。 Grab the instance method fun
from the GrandParent class, attach it to the current instance object self
and call it. 从GrandParent类中获取实例方法fun
,将其附加到当前实例对象self
并调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.