为什么不能将类用作模块? [英] Why can't classes be used as modules?

查看:86
本文介绍了为什么不能将类用作模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模块 Class 的超类:

Class.superclass
# => Module

在OOP中,这表示 Class 可以在每个可以使用 Module 实例的地方使用。

In OOP, this implies that an instance of Class can be used in every place where an instance of Module can be used.

令人惊讶的是,这是Ruby中的 Class 实例不是这种情况:

Surprisingly, this is not the case with Class instances in 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原理的原因是什么?为什么不能将类用作模块?

What is the reason for the violation of this OOP principle? Why can't classes be used as modules?

推荐答案


在OOP中,这意味着一个实例可以在每个可以使用Module实例的地方使用Class of Class。

In OOP, this implies that an instance of Class can be used in every place where an instance of Module can be used.

您正在混淆sub 类型和sub ,即子类型化(关于合同的细化)和继承(关于差分代码的重用)。

You are confusing subtypes and subclasses, i.e. subtyping (which is about refinement of contracts) and inheritance (which is about differential code re-use).

在Ruby中,继承会创建一个子类,但不会创建子类型。 (实际上,类型是只存在于Ruby程序员的脑海中的概念。)

In Ruby, inheritance creates a subclass, but not a subtype. (In fact, "type" is a concept that exists only in the programmer's head in Ruby.)

Class<模块是不是子类型的子类的一个示例,并且 StringIO < ;: IO 是不是子类的子类型的示例。

Class < Module is one example of a subclass that is not a subtype, and StringIO <: IO is an example of a subtype that is not a subclass.


违反此OOP原理的原因是什么?

What is the reason for the violation of this OOP principle?

这不是面向对象的原则。子类型和OO完全正交。有没有子类型的OO语言以及有子类型的非OO语言。

It's not an OO principle. Subtyping and OO are completely orthogonal. There are OO languages without subtyping as well as non-OO languages with subtyping.

注意:实际上这很容易将模块和类合为一体。它们可以互相继承,就像类从类继承以及类从模块继承一样。

Note: it would actually be easy to collapse modules and classes into one. They could inherit from each other both the same way as classes inherit from classes as well as the way classes inherit from modules.

这篇关于为什么不能将类用作模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆