是否有充分的理由让“私有"以其在Ruby中的方式工作? [英] Are there good reasons for 'private' to work the way it does in Ruby?

查看:54
本文介绍了是否有充分的理由让“私有"以其在Ruby中的方式工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了一段时间才了解 private 方法在Ruby中的工作方式,这确实让我感到非常尴尬.有谁知道以私人方式处理私人方法是否有充分的理由?这仅仅是历史原因吗?还是执行原因?还是有良好的逻辑依据(例如语义)?

It took me a while to understand how private methods work in Ruby, and it really strikes me as being very awkward. Does anyone know if there are good reasons for private methods to be handled the way they are? Is it just historic reasons? Or implementation reasons? Or are there good solid logical reasons (ie. semantic)?

例如:

class Person
  private
  attr_reader :weight
end

class Spy < Person
 private
  attr_accessor :code
 public
  def test
    code          #(1) OK: you can call a private method in self
    Spy.new.code  #(2) ERROR: cannot call a private method on any other object
    self.code     #(3) ERROR!!! cannot call a private method explicitly on 'self'
    code="xyz"    #(4) Ok, it runs, but it actually creates a local variable!!!
    self.code="z" #(5) OK! This is the only case where explicit 'self' is ok
    weight        #(6) OK! You can call a private method defined in a base class
  end
end

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆