ruby 中的对象如何拥有类方法?
Object 、 Class 、 Module 、 NilClass 都是 Class 的实例。
1)首先怀疑某物如何能够成为其自身的实例? (即“Class”是“Class”的实例)
还是我的假设错误?
2)如果对象、类、模块等都是对象,那么它们怎么可能有类方法?因为类方法只能从类中调用,并且不存在于对象中。 (或者我的断言 Object、Class 、 Module 都是对象是不正确的吗?)
3)如果 Object 、 Class 、 Module 不是对象那么它们是什么?
3) 类方法是否会导致 Class
的实例 a
中缺少方法并最终导致方法数量减少?
>> Class.methods.count
=> 82
>> a = Class.new
=> #<Class:0x1005519b8>
>> a.methods.count
=> 81
Object , Class, Module , NilClass are all instances of Class.
1) First Doubt how can something be an instance of itself ? (i.e 'Class' is an instance of 'Class')
or is my assumption wrong ?
2) If Object , Class ,Module etc ... are all objects then how can they have class methods ? Because class methods can only be called from classes and are not present in objects. (or is my assertion incorrect that Object, Class , Module are all objects ?)
3)If Object , Class , Module are not objects then what are they ?
3) Does a class method account for the missing method in instance a
of Class
and ultimately a decrease in method count ?
>> Class.methods.count
=> 82
>> a = Class.new
=> #<Class:0x1005519b8>
>> a.methods.count
=> 81
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
类对象确实是对象。
类方法实际上是在类的特征类(单例类)中定义的方法。这就是为什么这些方法不可用于所述类的实际实例。
这里有一个方法可以帮助您了解这一点:首先,添加一个
singleton_class
方法(如果您还没有):现在,尝试以下操作:
这将帮助您了解哪些方法可以用于类的实例,与类上的方法(即类的单例类的实例)的比较。
(您可以将
false
参数传递给每个instance_methods
调用,以查看为该类而不是任何超类定义了哪些方法。)Class objects are indeed objects.
Class methods are actually methods defined in the class's eigenclass (singleton class). That is why those methods are not available to actual instances of said classes.
Here's a way to help you see this: first, add a
singleton_class
method if you don't already have it:Now, try the following:
This will help you gain an appreciation for what methods are available to instances of a class, versus what methods are methods on the class (i.e., instances of the class's singleton class).
(You can pass a
false
argument to each of thoseinstance_methods
calls to see which methods are defined for that class, and not any superclasses.)Ruby核心由
Class
、Object
、Module
和Kernel
组成。它们是预定义的,因此Class
类可以是其自身的实例。它们有类方法,因为它们也是类(类是对象)。
我还无法回答。我必须找出答案中缺少哪种思考方法。
The Ruby core is composed by
Class
,Object
,Module
andKernel
. They're predefined, so theClass
class can be an instance of itself.They have class methods because they're classes, too (and classes are objects).
I can't answer it yet. I have to discover which method is missing to think in an answer.