类与模块方法的实例方法
我正在阅读Ruby的模块方法的这个解释,以及它们与类的实例方法的不同之处。 这是我正在阅读的解释:
请记住,与实例方法不同,需要在模块本身上定义模块方法。 你如何访问该模块? 回想一下,在模块定义中,self指的是被定义的模块。 因此,您需要使用self.xxxforms定义方法。
我不完全明白。 当我们在Classes中定义方法时,我们不必在类本身上定义它。 我们只是在类的实例化对象上调用它。
为什么我们需要使用术语“self”在模块本身上定义模块方法? 这是为了什么目的? 为什么我们不能在不使用术语self的情况下定义模块方法? 以下是我的模块框架的外观:
module GameTurn def self.take_turn(player) end
有两种module
方法:
- 那些打算混合到其他模块或类中的:“Mixins”
- 那些打算直接使用的:“暴露方法”
例如:
module Example def self.exposed_method # This method is called as Example.exposed_Method end def mixin_method # This method must be imported somewhere else with include or extend # or it cannot be used. end end
你也有两个class
:
- 仅在类的实例上调用的那些:“实例方法”
- 直接在课堂上调用的那些:“类方法”
- 这些在其他语言中也称为“静态方法”。
例:
class ExampleClass def self.class_method # This can be called as ExampleClass.class_method end def instance_method # This can only be called on an instance: ExampleClass.new.instance_method end end