gpt4 book ai didi

ruby - Ruby 中的“super”和继承

转载 作者:数据小太阳 更新时间:2023-10-29 07:27:54 24 4
gpt4 key购买 nike

在下面的类继承设计中,类B继承了类A,并对其方法的参数求值:

class A
def method_1(arg)
puts "Using method_1 with argument value '#{arg}'"
end

def method_2(arg)
method_1(arg)
end
end

class B < A
def method_1()
super("foo")
end

def method_2()
super("bar")
end
end

这是我尝试时得到的结果:

inst_A = A.new
inst_A.method_1("foo")
# >> Using method_1 with argument value 'foo'
inst_A.method_2("bar")
# >> Using method_1 with argument value 'bar'

我不再理解这个:

inst_B = B.new
inst_B.method_1
# >> Using method_1 with argument value 'foo'
inst_B.method_2
# >> Error: #<ArgumentError: wrong number of arguments (1 for 0)>
# >> <main>:11:in `method_1'
# >> <main>:6:in `method_2'
# >> <main>:16:in `method_2'

为什么在调用 B#method_2 时调用了 B#method_1,而不是 A#method_1

最佳答案

我修改了您的示例以打印出 A#method_1 中的当前类

def method_1(arg)
puts "Using method_1 from class: '#{self.class}' with argument value '#{arg}'"
end

如果您调用 B#method_1,您将获得此输出

Using method_1 from class: 'B' with argument value 'foo'

如您所说,它正在调用 B#method_1(覆盖 A#method_1)。这同样适用于 B#method_2 调用 super,然后尝试调用 self#method_1,它不带任何参数。 self 在这种情况下是 B 类型,并且 B 覆盖 method_1 以不接受任何参数。

Ruby 首先尝试在 self 中找到方法,如果找到则调用它,否则它会查找该对象的 ancestors 并调用它找到的方法的第一个版本.在你的例子中,selfmethod_1 没有参数,记住 Ruby 不支持方法重载(除非你使用可选参数)。

关于ruby - Ruby 中的“super”和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50233246/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com