类/对象悖论混淆 [英] The Class/Object Paradox confusion

查看:41
本文介绍了类/对象悖论混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 The Well Grounded Rubyist 一书中(
(来源:phrogz.net)

所有对象实例都继承自Object.所有的类都是对象,而Class 是一个类,因此Class 是一个对象.但是,对象实例继承自它们的类,而ObjectClass 类的实例,因此Object 本身从Class 获取方法.

然而,正如您在图中所见,没有循环查找循环,因为每个类都有两个不同的继承部分":实例方法和类"方法.最终,查找路径是理智的.

注意:此图反映了 Ruby 1.8,因此不包括 Ruby 1.9 中引入的核心 BasicObject 类.

In the book The Well Grounded Rubyist (excerpt), David Black talks about the "Class/Object Chicken-and-Egg Paradox". I'm having a tough time understanding the entire concept.

Can someone explain it in better/easier/analogical/other terms?

Quote (emphasis mine):

The class Class is an instance of itself; that is, it’s a Class object. And there’s more. Remember the class Object? Well, Object is a class... but classes are objects. So, Object is an object. And Class is a class. And Object is a class, and Class is an object.

Which came first? How can the class Class be created unless the class Object already exists? But how can there be a class Object (or any other class) until there’s a class Class of which there can be instances?

The best way to deal with this paradox, at least for now, is to ignore it. Ruby has to do some of this chicken-or-egg stuff in order to get the class and object system up and running—and then, the circularity and paradoxes don’t matter. In the course of programming, you just need to know that classes are objects, instances of the class called Class.

(If you want to know in brief how it works, it’s like this: every object has an internal record of what class it’s an instance of, and the internal record inside the object Class points back to Class.)

解决方案

You can see the problem in this diagram:


(source: phrogz.net)

All object instances inherit from Object. All classes are objects, and Class is a class, therefore Class is an object. However, object instances inherit from their class, and Object is an instance of the Class class, therefore Object itself gets methods from Class.

As you can see in the diagram, however, there isn't a circular lookup loop, because there are two different inheritance 'parts' to every class: the instance methods and the 'class' methods. In the end, the lookup path is sane.

N.B.: This diagram reflects Ruby 1.8, and thus does not include the core BasicObject class introduced in Ruby 1.9.

这篇关于类/对象悖论混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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