为什么我们定义`#initialize`而不是`:: new` [英] Why we define `#initialize` instead of `::new`

查看:42
本文介绍了为什么我们定义`#initialize`而不是`:: new`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,当创建一个新类时,我们将如下定义构造方法:

In Ruby, when making a new class, we will define the constructor method like so:

class Thing
  def initialize
     do_stuff
  end
end

但是,当实际创建对象的实例时,我们发现自己不是在实例上调用 initialize ,而是在类上调用 new .

However, when actually making an instance of the object, we find ourselves not calling initialize on the instance but new on the class.

是这种情况,为什么我们不定义 :: new ?

That being the case, why don't we instead define ::new?

class Thing
   def self.new
     do_stuff
   end
end

是否存在 :: new 某些东西,而不包含 initalize 未定义的场景?那两个完全不同吗?定义 :: new 是否可行?还是仅仅是 def初始化比(coded)短于 def self.new ?

Is there something ::new does beind the scenes that initalize doesn't define? Are those two different at all? Would defining ::new work? Or is it just that def initialize is shorter (not) than def self.new?

我认为这种差距一定有充分的理由.

I'm thinking there must be a good reason for the disparity.

推荐答案

New为新对象分配空间并创建它.然后,它调用Objects的initialize方法以使用分配的内存创建一个新的Object.通常,您想要自定义的唯一部分就是实际的创建,并且很乐意将落后的内存分配留给Object.new方法,因此您编写了一个initialize方法.幕后的新功能看起来像这样(C语言除外):

New allocates space for the new object and creates it. It then calls the Objects initialize method to create a new Object using the allocated memory. Usually, the only part you want to customize is the actual creation, and are happy to leave the behind memory allocation to the Object.new method, so you write an initialize method. What new is doing under the hood looks something like this (except in C):

 class Object
    def self.new(*args, &block)
        object = allocate
        object.send(:initialize, *args, &block)
        return object
    end
 end

因此,当您调用Object.new时,实际发生的是:

So when you call Object.new, what actually happens is:

1)分配了内存2)调用对象的initialize方法.

1) Memory is allocated 2) The objects initialize method is called.

这篇关于为什么我们定义`#initialize`而不是`:: new`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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