zoukankan      html  css  js  c++  java
  • Ruby的private和protected

    今天,下面这段程序让我纠结了很久,Ruby中private的概念真的很奇怪。。。

    class Test private
      def test_print
        puts 'test'
      end
    end
    
    class Test2 < Test
      def test_print2
        # self.test_print #=> 这里加上self就不能调用,private method `test_print' called for # (NoMethodError)
        test_print #=> 不加self就能调用
      end
    end
    
    Test2.new.test_print2 

    为什么不加self的话,private也可以调用父类的方法呢?

    原来在Ruby中,private和Java或者其他语言不一样,子类也可以调用,只是不能指定调用者。

    翻了下《The Ruby Way》,书上说:

    private:类和子类都能调用,但是private方法不能指定调用者,默认为self。

    protected:类和子类都能调用,可以指定调用者。

    这就解释了为什么上面的代码中,用self调用会出错,而不加self就能正确执行。

  • 相关阅读:
    各进制转换
    免root xshell连接termux
    sqlmap怎么拿shell
    SSRF漏洞
    国外安全网站、社区论坛、博客、公司、在线工具等整合收集
    渗透测试常用工具问题总结
    cdn绕过
    xss注入
    永恒之蓝(msf17010)kali复现
    文件上传漏洞和绕过
  • 原文地址:https://www.cnblogs.com/betarabbit/p/2761716.html
Copyright © 2011-2022 走看看