类的实例方法与模块方法 [英] instance methods of classes vs module methods

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

问题描述

我正在阅读有关Ruby的模块方法的说明,以及它们与类的实例方法有何不同.这是我正在阅读的说明:

I am reading this explanation of module methods for Ruby and how they are different from instance methods for classes. Here is the explanation I am reading:

请记住,与实例方法不同,模块方法需要 在模块本身上定义.您如何访问该模块?记起 在模块定义中,自我是指模块 定义.因此,您需要使用self.xxx形式定义方法.

Remember that unlike an instance method, a module method needs to be defined on the module itself. How do you access the module? Recall that inside a module definition, self refers to the module being defined. So you'll need to define the method using the form self.xxx.

我不完全明白.当我们在类中定义方法时,我们不必在类本身上定义它.我们只是在类的实例化对象上调用它.

I don't totally get it. When we defined methods inside Classes, we didn't have to define it on the class itself. We merely called it on the instantiated objects of the classes.

为什么我们需要使用术语自我"在模块本身上定义模块方法?目的是什么?为什么我们不能不使用术语自我"就直接定义模块方法?这是我的模块骨架的外观:

Why do we need to define module methods on the module itself using the term "self"? What's the purpose of this? Why can't we just define module methods without using the term self? Here is how my module skeleton looks:

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上也有两个:

  • 仅在类实例方法"的实例上调用的那些对象
  • 直接在类上调用的那些:类方法"
    • 在其他语言中,这些也称为静态方法".
    • Those that are called only on instances of the class: "Instance methods"
    • Those that are called directly on the class: "Class methods"
      • These are also called "static methods" in other languages.

      示例:

      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
      

      这篇关于类的实例方法与模块方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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