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

Ruby如何处理嵌套类的继承?

发布时间:2020-12-17 03:20:28 所属栏目:百科 来源:网络整理
导读:在以下测试用例中: class Package class Component def initialize p [:initialize,self] end endendclass Package_A Packageendclass Package_B Packageend# Why are the following components of type Package and not Package_A and Package_Bcomponent=
在以下测试用例中:

class Package
    class Component
        def initialize
            p [:initialize,self]
        end
    end
end

class Package_A < Package
end

class Package_B < Package
end

# Why are the following components of type Package and not Package_A and Package_B
component=Package_A::Component.new
p component

component=Package_B::Component.new
p component

结果是:

[:initialize,#<Package::Component_1:0x2c0a8f8>]
#<Package::Component:0x2c0a8f8>
[:initialize,#<Package::Component_1:0x2c0a5b0>]
#<Package::Component:0x2c0a

如何获取特定的Package_A.component和Package_B.component?

解决方法

Class Component在Package中声明,所以看起来是正确的. ::告诉在Package_A范围内查找名称Component.由于那里没有Component,它会查找超类.

这个例子展示了如何实现你想要的.可能有一种更简单的方法,我很乐意看到它.

class Package
  class Component
    def foo
      puts "bar"
    end
  end
end

class Pack_a < Package
end

Pack_a::Component.new.foo
#=> bar
# as expected,though we actually have Package::Component

class Pack_b < Package
  class Component
  end
end

Pack_b::Component.new.foo
#=> NoMethodError: undefined method 'foo' for Pack_b::Component
# this error is because Pack_b::Component has nothing to do with Package::Component

class Pack_c < Package
  class Component < Package::Component
  end
end

Pack_c::Component.new.foo
#=> bar
# as expected

Pack_c::Component.new
#=> Pack_c::Component
# this Component is a subclass of Package::Component

这更应该解释范围如何在这种情况下起作用.希望这可以帮助.

(编辑:李大同)

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

    推荐文章
      热点阅读