Confusion with singleton method defined on `Class` object

ε祈祈猫儿з 提交于 2019-12-24 12:38:26

问题


What I know singleton methods can be called by the objects, on which it is defined. Now in the below example C is also an object of Class and singleton method a_class_method defined on the Class object C. So how does another Class object D able to call a_class_method?

How does object individuation principle holds in this example?

class C
end
#=> nil

def C.a_class_method
 puts "Singleton method defined on #{self}"
end
#=> nil

C.a_class_method
#Singleton method defined on C
#=> nil

class D < C
end
#=> nil

D.a_class_method
#Singleton method defined on D
#=> nil

回答1:


well when you did the < you made class D inherit from Class C so D will get anything from class C. If you want to know what all D's parents are you can do

puts "D's parent Classes = #{D.ancestors.join(',')}"

which will give you

D's parent Classes = D,C,Object,Kernel

So even though D would be an individual class it is a sub class of C which is what lets it use a method defined for C




回答2:


The reason that a_class_method is available is that:

D.singleton_class.superclass == C.singleton_class
 # => true


来源:https://stackoverflow.com/questions/15419429/confusion-with-singleton-method-defined-on-class-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!