加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby中的’超级’和继承

发布时间:2020-12-17 03:08:01 所属栏目:百科 来源:网络整理
导读:在下面的类继承设计中,类B继承了类A,并对其方法的参数进行了评估: class A def method_1(arg) puts "Using method_1 with argument value '#{arg}'" end def method_2(arg) method_1(arg) endendclass B A def method_1() super("foo") end def method_2()
在下面的类继承设计中,类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而不是A#method_1时调用B#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 overrode method_1不带参数.

Ruby首先尝试在self中找到该方法并在找到它时调用它,否则它会查看该对象的祖先并调用它找到的方法的第一个版本.在你的情况下,self有method_1,它不带参数,并且记住Ruby不支持方法重载(除非你使用可选参数).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读