ruby 类方法,实例方法,单例方法

类方法只有类本身可以调用,在ruby中,类方法是一种特殊的单例方法

从上一篇eigenclass中可以得到这样的结论,eigenclass也是一种类,在ruby中所有的类又都是对象,对象都有对应的eigenclass。。。

 

【例1】

 

 

class C
  def a_method
    puts "C#a_method"
  end

  def self.a_class_method
    puts "C#a_class_method"
  end
end

class D < C
  
end

obj = D.new
obj.a_method
puts D.a_class_method


class Object
  def eigenclass
    class << self
      self
    end
  end
end

class << obj
  def a_singleton_method
    puts 'obj#a_singleton_method'
  end
end

puts obj.a_singleton_method
puts obj.eigenclass
puts obj.eigenclass.superclass
 

 

 

1.定义类C,实例方法a_method和类方法a_class_method

2.定义类D, 继承自类C

3.创建类D的实例对象obj,并给obj添加单例方法a_singleton_method

 

 

C#a_method
C#a_class_method

obj#a_singleton_method
#<Class:#<D:0x2893c38>>
#<Class:D>
 

 

结合关系图和运行结果来分析一下,实例方法,类方法,单例方法的调用过程,及存在位置

方法的查找方式: one step to the right, then up, 直译: 向右一步(进入到eigenclass中查找),然后向上(父类中查找)

 


ruby 类方法,实例方法,单例方法_第1张图片

 

注释: 以#号标示的是eigenclass, c标示 (eigen)class, s表示 superclass

 

图中可以看出,对象有其自身的eigenclass, 类也是对象,也有对应的eigenclass

与之前不同方法的查找位置有一点不同,首先会去对象对应的eigenclass中查找,在到ancestors中查找

 

 

puts D.a_class_method 

#C#a_class_method

 

 

D调用类方法a_class_method时, 输出了C#a_class_method,说明在D中可以调用父类的类方法

从图中看,执行D.a_class_method时,ruby会先去D类对应的eigenclass中查找,再到其父类中查找

 

(类方法存在于 类对应eigenclass中,和单例方法比较像,所以可以理解为类方法是一种特殊的单例方法) 

 

你可能感兴趣的:(method,Class,Metaprogramming,eigenclass)