类/对象悖论混淆 [英] The Class/Object Paradox confusion
问题描述
在 The Well Grounded Rubyist 一书中(
(来源:phrogz.net)
所有对象实例都继承自Object
.所有的类都是对象,而Class
是一个类,因此Class
是一个对象.但是,对象实例继承自它们的类,而Object
是Class
类的实例,因此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 aClass
object. And there’s more. Remember the classObject
? Well,Object
is a class... but classes are objects. So,Object
is an object. AndClass
is a class. AndObject
is a class, andClass
is an object.Which came first? How can the class
Class
be created unless the classObject
already exists? But how can there be a classObject
(or any other class) until there’s a classClass
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 toClass
.)
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屋!