类,模块,其特征类和方法查找 [英] Class, Module, their eigenclasses, and method lookup

查看:93
本文介绍了类,模块,其特征类和方法查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们打开类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中查找方法(因为ClassBasicObject本征类的超类),然后到它的超类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屋!

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