Ruby中的多重inheritance?

我认为Ruby除了mixin之外只允许单inheritance。 但是,当我有inheritance类ThingSquare时, Thing依次inheritanceObject

 class Thing end class Square < Thing end 

这不代表多重inheritance吗?

我认为你正在以错误的方式理解多重inheritance的含义。 可能你想到的是多重inheritance是这样的:

 class A inherits class B class B inherits class C 

如果是这样,那就错了。 这不是多inheritance的原因,Ruby也没有问题。 多重inheritance的真正含义是:

 class A inherits class B class A inherits class C 

你肯定不能用Ruby做到这一点。

不,多inheritance意味着一个类有多个父类。 例如,在ruby中,您可以使用以下模块执行该行为:

 class Thing include MathFunctions include Taggable include Persistence end 

所以在这个例子中Thing类将有一些来自MathFunctions模块,Taggable和Persistence的方法,这些方法使用简单的类inheritance是不可能的。

如果B类inheritance自A类,则B的实例具有A类和B类行为

 class A end class B < A attr_accessor :editor end 

Ruby具有单一inheritance,即每个类只有一个父类。 Ruby可以使用模块(MIXIN)模拟多重inheritance

 module A def a1 end def a2 end end module B def b1 end def b2 end end class Sample include A include B def s1 end end samp=Sample.new samp.a1 samp.a2 samp.b1 samp.b2 samp.s1 

模块A由方法a1和a2组成。 模块B由方法b1和b2组成。 类Sample包括模块A和B. Sample类可以访问所有四种方法,即a1,a2,b1和b2。 因此,您可以看到类Sampleinheritance自两个模块。 因此,您可以说类Sample显示多重inheritance或mixin。

多重inheritance – 这在ruby中绝对不可能,甚至模块都没有。

多级inheritance – 即使使用模块,这也是可能的。

为什么?

模块充当包含它们的类的绝对超类。

例1:

 class A end class B < A end 

这是一个普通的inheritance链,你可以通过祖先来检查它。

B.ancestors => B - > A - >对象 - > ..

模块inheritance -

例2:

 module B end class A include B end 

以上示例的inheritance链 -

B.ancestors => B - > A - >对象 - > ..

这与Ex1完全相同。 这意味着模块B中的所有方法都可以覆盖A中的方法,并且它充当真正的类inheritance。

例3:

 module B def name p "this is B" end end module C def name p "this is C" end end class A include B include C end 

A.ancestors => A - > C - > B - >对象 - > ..

如果你看到最后一个例子,即使包含两个不同的模块,它们也在一个inheritance链中,其中B是C的超类,C是A的超类。

所以,

 A.new.name => "this is C" 

如果从模块C中删除name方法,则上面的代码将返回“this is B”。 这与inheritance一个类相同。

所以,

在任何时候,ruby中只有一个多级inheritance链,它会使该类具有多个直接父级