为什么我可以像调用实例方法一样调用类方法? [英] Why am I able to call the class method as if it were an instance method here?

查看:61
本文介绍了为什么我可以像调用实例方法一样调用类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览这个例子:

class SQLObject
  def self.columns
    return @columns if @columns
    columns = DBConnection.execute2(<<-SQL).first
      SELECT
        "#{table_name}".*
      FROM
        "#{table_name}"
      LIMIT
        0
    SQL
    columns.map!(&:to_sym)
    @columns = columns
  end

  def self.table_name
    @table_name ||= self.name.underscore.pluralize
  end

  def insert
    column_symbols = self.class.columns.drop(1)
    column_names = column_symbols.map(&:to_s).join(", ")
    question_marks = (['?'] * column_symbols.count).join(", ")
    DBConnection.execute(<<-SQL, *attribute_values)
      INSERT INTO
        #{self.class.table_name} (#{column_names})
      VALUES
        (#{question_marks})
    SQL
    self.id = DBConnection.last_insert_row_id
  end
end

我很困惑为什么可以在self.columns"方法中调用 table_name 方法,就好像它是一个实例方法一样.table_name"方法不是类方法吗?因此,它不应该在self.columns"方法中也称为self.class.table_name"吗?

And I was confused as to why it's ok to call the table_name method in the "self.columns" method as if it were an instance method. Isn't the "table_name" method a class method? Hence, shouldn't it be called as "self.class.table_name" in the "self.columns" method as well?

推荐答案

在抽象类中时,self 指的是正确的类,而不是对象.这就是为什么您无需明确告诉 self

When inside an abstract class, the self refers to the proper class, not the object. That's why you can access the method without explicitly telling self

这篇关于为什么我可以像调用实例方法一样调用类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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