当我在上面创建对象时,是否首先调用initliase方法?在PHP中,我们有一个叫做构造函数的东西,每当创建一个对象时都先运行,如果类中有多个方法,在ruby中首先调用哪个方法怎么办?
谢谢。
与任何其他方法一样,Class#new
只是一种常规方法。它看起来有点像这样,虽然在大多数实现中它实际上不是用Ruby编写的:
class Class
def new(*args, &block)
new_obj = allocate
new_obj.initialize(*args, &block)
# actually, `initialize` is private, so it's more like this instead:
# new_obj.__send__(:initialize, *args, &block)
return new_obj
end
end
文档也清楚地说:
new(args, …)
→obj
调用
allocate
创建类的类的新对象,然后调用该对象的initialize
方法,传递它args。这是在使用.new
构造对象时最终调用的方法。
以下是各种实现中Class#new
的源代码:
machine/builtin/class.cpp
core/src/main/java/org/jruby/RubyClass.java
topaz/objects/classobject.py
src/kernel/bootstrap/Class.rb
object.c
(顺便说一下,你会注意到这个方法是在object.c
中定义的,而不是在class.c
中。这是我不喜欢看YARV的实现细节的原因之一,而是看看Rubinius,JRuby,IronRuby或Topaz他们的组织得好得多。)每次调用initialize
时都会调用new
方法。
应该在代码中调用该类中声明的任何其他方法。
例如:
class Example
def initialize
#some initialization code here
puts "initialize method has just been called"
end
def foo
#some foo code
puts "this is the foo method"
end
end
然后,在你的代码中:
my_obj = Example.new #initialize method will be called here
my_obj.foo #now the foo method will be called
这就是它,祝你好运!