为什么Class是Class的实例,而不是Object的实例? [英] Why is Class an instance of Class, and not of Object?

查看:38
本文介绍了为什么Class是Class的实例,而不是Object的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Class.instance_of?(Object)返回 false ,而 Class.instance_of?(Class)返回 true .我觉得这很奇怪,因为我认为 Class 作为一个对象,必须是 Object 类的一个实例.怎么可以成为自己的实例?

Class.instance_of?(Object) returns false, while Class.instance_of?(Class) returns true. I find this surprising because I thought Class, being an object, had to be an instance of the Object class. How can it be an instance of itself?

但是,假设 Class Object 类的一个实例,似乎会导致更令人困惑的问题.由于 Object 是一个类,因此它必须是 Class 类的实例.这是怎么回事?

But assuming that Class is an instance of the Object class seems to lead to an even more confusing issue; since Object is a class, it has to be an instance of the Class class. What is going on here?

推荐答案

Ruby中的类是一流的对象:每个都是类 Class

Classes in Ruby are first-class objects: each is an instance of class Class

因此,您定义的每个类都为您提供:

So every class you define gives you:

  > MyClass.instance_of?(Class)
  => true

在此页面上查看带有继承的图: http://ruby-doc.org/core-2.2.3/Class.html

Check out the diagram with the inheritance on this page: http://ruby-doc.org/core-2.2.3/Class.html

类,模块和对象是相互关联的.在下面的图中,垂直箭头表示继承,而圆括号是元类.所有元类都是类'Class'的实例.

Classes, modules, and objects are interrelated. In the diagram that follows, the vertical arrows represent inheritance, and the parentheses metaclasses. All metaclasses are instances of the class `Class'.

                         +---------+             +-...
                         |         |             |
         BasicObject-----|-->(BasicObject)-------|-...
             ^           |         ^             |
             |           |         |             |
          Object---------|----->(Object)---------|-...
             ^           |         ^             |
             |           |         |             |
             +-------+   |         +--------+    |
             |       |   |         |        |    |
             |    Module-|---------|--->(Module)-|-...
             |       ^   |         |        ^    |
             |       |   |         |        |    |
             |     Class-|---------|---->(Class)-|-...
             |       ^   |         |        ^    |
             |       +---+         |        +----+
             |                     |
obj--->OtherClass---------->(OtherClass)-----------...

这意味着:

  > Class.ancestors 
  => [Class, Module, Object, Kernel, BasicObject]

  > Class.superclass
  => Module
  > Module.superclass
  => Object
  > Object.superclass
  => BasicObject
  > BasicObject.superclass
  => nil

为了对此有更深入的了解,我强烈推荐戴夫·托马斯(Dave Thomas)的电视广播系列: Ruby对象模型和元编程

To get a deeper understanding of this, I highly recommend Dave Thomas's screencast series: The Ruby Object Model and Metaprogramming

这篇关于为什么Class是Class的实例,而不是Object的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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