Module
是的超类Class
:
Class.superclass
# => Module
在面向对象编程中,这意味着Class
可以在任何有实例的地方使用Module
可以使用。
令人惊讶的是,情况并非如此Class
Ruby 中的实例:
class C end
c = C.new
module M end
# Let's do all the extend/include/prepend stuff with M!
c.extend M
C.include M
C.prepend M
# All worked fine until this line.
# Let's turn to classes now!
# First, get a class to work with.
class C_as_M end
C_as_M.class.superclass
# => Module # yes, C_as_M is an instance of a Module child
C_as_M.is_a? Module
# => true # yes, it is still a Module
# And now let's do the same extend/include/prepend stuff with C_as_M!
c.extend C_as_M
# => TypeError: wrong argument type Class (expected Module)
C.include C_as_M
# => TypeError: wrong argument type Class (expected Module)
C.prepend C_as_M
# => TypeError: wrong argument type Class (expected Module)
违反这个OOP原则的原因是什么?为什么类不能用作模块?
在 OOP 中,这意味着可以在可以使用 Module 实例的每个地方使用 Class 实例。
你很困惑子types and subclasses,即子类型(关于契约的细化)和继承(关于差异代码重用)。
在 Ruby 中,继承创建子类,但不创建子类型。 (事实上,“类型”是 Ruby 中只存在于程序员头脑中的概念。)
Class < Module
是不是子类型的子类的一个示例,并且StringIO
<: IO
是不是子类的子类型的示例。
违反这个OOP原则的原因是什么?
这不是 OO 原则。子类型和面向对象是完全正交的。有不带子类型的 OO 语言,也有带子类型的非 OO 语言。
注意:实际上很容易将模块和类合二为一。它们可以以与类从类继承以及类从模块继承的方式相同的方式相互继承。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)