Sta*_*lin 27 ruby oop constructor initialization new-operator
我该如何调用父母构造函数?
module C
attr_accessor :c, :cc
def initialization c, cc
@c, @cc = c, cc
end
end
class B
attr_accessor :b, :bb
def initialization b, bb
@b, @bb = b, bb
end
end
class A < B
include C
attr_accessor :a, :aa
def initialization (a, b, c, aa, bb, cc)
#call B::initialization - ?
#call C::initialization - ?
@a, @aa = a, aa
end
end
Run Code Online (Sandbox Code Playgroud)
谢谢.
Jör*_*tag 38
Ruby没有构造函数,因此显然不可能调用它们,父类或其他方式.但是,Ruby 确实有方法,为了使用与当前正在执行的方法相同的名称调用父方法,可以使用super关键字.[注意:super不带参数是传递传递给当前正在执行的方法的相同参数的快捷方式.如果你真的想传递没有参数,你必须明确地这样做:super().]
mač*_*ček 29
使用super方法!但Ruby没有多重继承.
class B
attr_accessor :b, :bb
def initialize(b, bb)
@b, @bb = b, bb
end
end
module C
end
class A < B
include C # <= if C was a class, you'd get: TypeError: wrong argument type Class (expected Module)
attr_accessor :a, :aa
def initialize(a,b,aa,bb)
@a, @aa = a, aa
super(b, bb) # <= calls B#initialize
end
end
a = A.new(1,2,3,4)
puts a.inspect # => #<A:0x42d6d8 @aa=3, @a=1, @b=2, @bb=4>
Run Code Online (Sandbox Code Playgroud)
Pet*_*ter 25
首先,你的方法应该是initialize,而不是initialization.然后,您可以使用super调用父类方法.至于调用C初始化程序A,为清楚起见,我建议将初始化内容拆分为不同的函数,然后直接调用该函数.它易于实现,更清晰.
以下代码将打印:
A.proc1 B.proc1 C.proc1
module A
def proc1
puts "A.proc1"
super
end
end
class B
def proc1
puts "B.proc1"
end
end
class C < B
include A
def proc1
super
puts "C.proc1"
end
end
C.new.proc1
Run Code Online (Sandbox Code Playgroud)