新手问题 新手,想请教关于方法的访问调用

Evilcrow · February 04, 2018 · Last by Evilcrow replied at February 04, 2018 · 1033 hits

刚开始学 Ruby,还不熟练,在看到方法的修饰符时,public,private,protected 其中提到了对方法的访问与调用问题

class Person
  def a
    puts "a"
  end
  def b obj
    obj.a
  end
  protected :a
end

m = Person.new
n = Person.new
m.b n

上面的例子中,protected 方法不能直接被实例对象调用,但是可以被同父类的实例对象访问

我想问问大家,

  1. 对方法的访问到底是什么意思,与调用有何区别

  2. 上面是实例对象 n 访问 a 方法,访问的形式是obj.a

    那实际上访问到底有没有发生调用

百度了许多,google 试了,效果也一般,谢谢大家

https://launchschool.com/books/oo_ruby/read/inheritance#privateprotectedandpublic

private methods are not accessible outside of the class definition at all, and are only accessible from inside the class when called without self.

空行

from outside the class, protected methods act just like private methods; from inside the class, protected methods are accessible just like public methods.

访问就是调用,你太抠字眼了

3 Floor has deleted
Reply to Awlter1

明白了,一针见血,谢谢你了。

public, private, protected 解释的很清楚,

另外,还可以请教一下,哪里还有这么明了的资料吗?

Evilcrow closed this topic. 09 Feb 12:27
You need to Sign in before reply, if you don't have an account, please Sign up first.