手机
当前位置:查字典教程网 >脚本专栏 >ruby专题 >Ruby 之 class 中的 private、 protected、public
Ruby 之 class 中的 private、 protected、public
摘要:Privateprivate函数只能在本类和子类的上下文中调用,且只能通过self访问。这个意思就是:private函数,只能在本对象内部访...

Private

private 函数只能 在本类和子类的 上下文中调用,且只能通过self访问。

这个意思就是:private函数,只能在本对象内部访问到。

对象实例变量(@)的访问权限就是 private。

复制代码 代码如下:

class AccessTest

def test

return “test private”

end

def test_other(other)

“other object ”+ other.test

end

end

t1 = AccessTest.new

t2 = AccessTest.new

p t1.test # => test private

p t1.test_other(t2) # => other object test private

# Now make 'test' private

class AccessTest

private :test

end

p t1.test_other(t2) #错误 in `test_other': private method `test' called for #<AccessTest:0x292c14> (NoMethodError)

Protected

protect 函数只能 在本类和子类的 上下文中调用,但可以使用 other_object.function的形式。(这跟 C++ 的 private 模式等同)

这个的关键是 protected函数可以在同类(含子类)的其它对象的内部中使用。

# Now make 'test' protect

class AccessTest

protected:test

end

p t1.test_other(t2) # other object test private

Public

public 函数可以在任何地方调用。成员函数和常量的默认访问权限就是public。

【Ruby 之 class 中的 private、 protected、public】相关文章:

Ruby中的类Google Map/Reduce框架Skynet介绍

详解Ruby中的异常

详解Ruby on Rails中的mailer相关使用

实例解析Ruby中的数值类型以及常量

Ruby实现的矩阵连乘算法

Ruby中的钩子方法详解

Ruby on Rails中MVC结构的数据传递解析

详解Ruby中的单件方法和单件类

Ruby实现的删除已经合并的git分支脚本分享

Ruby中使用Block、Proc、lambda实现闭包

精品推荐
分类导航