如何调用父母构造函数?
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
感谢。
答案 0 :(得分:37)
Ruby没有构造函数,因此显然不可能调用它们,父类或其他方式。但是,Ruby 具有方法,并且为了使用与当前正在执行的方法相同的名称调用父方法,可以使用super
关键字。 [注意:不带参数的super
是传递传递给当前正在执行的方法的相同参数的快捷方式。如果您确实想要传递 no 参数,则必须明确地执行此操作:super()
。]
答案 1 :(得分:28)
使用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>
答案 2 :(得分:24)
首先,您的方法应该是initialize
,而不是initialization
。然后,您可以使用super
来调用父类方法。至于在C
中调用A
的初始化程序,为清楚起见,我建议将初始化内容拆分为不同的函数,然后直接调用该函数。它易于实现,更清晰。
答案 3 :(得分:7)
以下代码将打印:
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