类,模块,其特征类和方法查找 [英] Class, Module, their eigenclasses, and method lookup
问题描述
让我们打开类Module
并为其添加一个方法:
Let's open class Module
and add a method to it:
class Module
def foo
puts "phew"
end
end
我可以通过执行此操作来调用此方法,
I can call this method by doing this,
Class.foo
这是可以理解的,因为Class
的类是Class
,其超类是Module
.因此它可以调用在Module
中定义的实例方法.
which is understandable because class of Class
is Class
, whose superclass is Module
. so it can call instance methods defined in Module
.
现在,下面的方法bar
是在Module
的本征类上定义的:
Now, the method bar
below is defined on Module
's eigenclass:
class Module
def self.bar
puts "bar"
end
end
但现在
Class.bar
也可以.
有人可以向我解释Class
如何访问Module
本征类中的方法吗?
Can someone explain me how Class
can access methods in Module
's eigenclass?
我想我明白了.方法查找不像我之前解释的那样工作.当我执行Class.foo
时,将在Class
的本征类中搜索该方法,然后在BasicObject
的本征类中查找它的超类,直到BasicObject
的本征类为止.蛇吃它自己的尾巴)在Class
中查找方法(因为Class
是BasicObject
本征类的超类),然后到它的超类Module
,在其中找到方法.
I think I got it now. Method look up doesn't work the way I explained before. when I do Class.foo
, the method is searched in Class
's eigenclass and then it's superclass which is Module
's eigenclass all the way upto BasicObject
's eigenclass at which point it turns upon itself (like a serpent eating it's own tail) to look for method in Class
(as Class
is the superclass of BasicObject
's eigenclass) and then to it's superclass Module
, where it finds the method.
类似地,当我执行Class.bar
时,将在Class
的本征类中搜索方法,然后在Module
的本征类中找到该方法.
Similarly, when I do Class.bar
, method is searched in Class
's eigenclass and then in Module
's eigenclass where it finds it.
我这样做
class Class
def check
puts "class instance method"
end
end
和
class Module
def self.check
puts "modules eigenclass method"
end
def check
puts "module instance method"
end
end
我做的时候会猜出wot:
guess wot is the output when I do:
Class.check
这是我目前的理解:
This is my current understanding:
推荐答案
I recently wrote a pretty extensive tutorial, including new Ruby 2.0 behavior.
注意:在Ruby中使用的术语是singleton_class
,而不是eigenclass
.
Note: the term used in Ruby is singleton_class
, not eigenclass
.
这篇关于类,模块,其特征类和方法查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!