简体   繁体   English

红宝石:在没有父类的情况下调用super

[英]ruby: calling super without having a parent class

I have a class which overrides self.new and calls super in it, but the class doesn't derive from antoher class. 我有一个重写self.new并在其中调用super的类,但是该类不是从另一个类派生的。 So what exactly does the call? 那么电话到底是什么呢?

class Test
  attr_reader :blatt

  def self.new(blatt, quellformat, &block)
    begin
      # why can't I call initialize(blatt,quellformat) here? 
      # when I try this, it only prints "wrong # of arguments(2 for 1)"

      a = super(blatt, quellformat) # but this works...

      # some code
      a
    end
  end

  def initialize(blatt, quellformat)
    @name = blatt.blattname
    @datei = blatt.datei
    @blatt = blatt
    @qu = quellformat
  end
end

Classes inherit from Object by default. 默认情况下,类从Object继承。 Hence, your super call will call Object.new . 因此,您的super调用将调用Object.new

why can't I call initialize(blatt,quellformat) here? 为什么我不能在这里调用initialize(blatt,quellformat)

Because Test::new is a class method and Test#initialize is an instance method. 因为Test::new是类方法,而Test#initialize是实例方法。 You need an instance of your class to call initialize . 您需要一个类的实例才能调用initialize

By defining self.new , you're replacing Class#new . 通过定义self.new ,您将替换Class#new According to the documentation: 根据文档:

Calls allocate to create a new object of class ’s class, then invokes that object's initialize method, passing it args . 调用allocate创建的class的新对象,然后调用该对象的initialize方法,并将其传递给args

A Ruby implementation would look like this: Ruby实现如下所示:

def self.new(*args)
  obj = allocate
  obj.send(:initialize, *args)
  obj
end

Calling super simply invokes the default implementation, ie Class#new , which does the same. 调用super只会调用默认的实现,即Class#new ,它执行相同的操作。 Here's the C code: 这是C代码:

VALUE
rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
{
    VALUE obj;

    obj = rb_obj_alloc(klass);
    rb_obj_call_init(obj, argc, argv);

    return obj;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM