ruby - 子类中是否可以访问 Ruby 私有(private)方法?

标签 ruby private-methods

我有如下代码:

class A
  private
  def p_method
    puts "I'm a private method from A"
  end
end

class B < A
  def some_method
    p_method
  end
end

b = B.new
b.p_method    # => Error: Private method can not be called
b.some_method # => I'm a private method from A

b.some_method 调用类 A 中定义的私有(private)方法。如何在继承它的类中访问私有(private)方法?这种行为在所有面向对象的编程语言中都一样吗? Ruby 是如何进行封装的?

最佳答案

这是来自 this source 的简要说明:

  1. Public methods can be called by anyone---there is no access control. Methods are public by default (except for initialize, which is always private).
  2. Protected methods can be invoked only by objects of the defining class and its subclasses. Access is kept within the family.
  3. Private methods cannot be called with an explicit receiver. Because you cannot specify an object when using them, private methods can be called only in the defining class and by direct descendants within that same object.

这个来自类似问题的答案更详细地扩展了该主题:https://stackoverflow.com/a/1565640/814591

关于ruby - 子类中是否可以访问 Ruby 私有(private)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31217588/

相关文章:

python - python如何解析类中的私有(private)(双下划线)方法?

algorithm - 应用于私有(private)方法的单元测试

java - java中私有(private)方法下模拟外部调用

jmockit - 如何在 Jmockit 中模拟私有(private)方法时匹配 'any' 参数类型

ruby-on-rails - 清理网址

ruby-on-rails - Rails 在我的 View 中创建缩略图库

c++ - 可以通过强制转换为布局兼容类型来访问私有(private)成员函数吗?

ruby - "You don' 你的 PATH 中没有 [PATH ],gem 可执行文件将不会运行。 "while using "gem install --user-install bundler"

ruby-on-rails - Rails 默认错误页面在开发时不显示

ruby - 我如何处理rest-client 500错误响应并继续抓取我的循环?