如果创建一个类Foo
并定义一个被调用的函数initialize
和一个被调用的函数new
怎么办?
稍后,如果我编写代码foo = Foo.new
,将运行哪个函数?由于initialize
应该在声明时调用该函数new
。
编辑:
为了澄清:
class Foo
def new
end
end
这就是我所说的那种事情。
如果创建一个类Foo
并定义一个被调用的函数initialize
和一个被调用的函数new
怎么办?
稍后,如果我编写代码foo = Foo.new
,将运行哪个函数?由于initialize
应该在声明时调用该函数new
。
编辑:
为了澄清:
class Foo
def new
end
end
这就是我所说的那种事情。
If you defined new
on the class, it would call your function and override the typical new
method which would create a new instance of the class. It's better if you don't override it at all, but you can still do it and get away with it in Ruby because Ruby's nice like that.
If you still want a new instance of the class after that, you can call Foo.allocate
to get that. Then you can call initialize
on that object manually to trigger any initialization events.
new
做的时候不会调用手动定义的函数,Foo.new
因为手动定义new
的函数是实例函数。Foo.new
正在调用一个类函数。
class Foo
def new
puts 'new!'
123
end
def initialize
puts 'initialize'
end
end
c = Foo.new
puts c #this will print "#<Confusion:0xb75b20f4>"
c.new #this will print "new!"
编辑:
但是,如果我这样做了:
class Foo
def Foo.new
end
end
然后我们会遇到@Ryan 指出的问题。