Chinaunix首页 | 论坛 | 博客
  • 博客访问: 62216
  • 博文数量: 33
  • 博客积分: 841
  • 博客等级: 准尉
  • 技术积分: 340
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-20 20:54
文章分类

全部博文(33)

文章存档

2011年(33)

分类: Python/Ruby

2011-02-19 11:34:00

  1. class Test
  2.     def method1 #默认为公有方法
  3.     puts "This is a public method"
  4.     end

  5.     protected         #保护方法
  6.     def method2
  7.     puts "This is a protected method"
  8.     end
  9.     
  10.     private         #私有方法
  11.     def method3
  12.     puts "This is a private method"
  13.     end

  14.     public    
  15.     def test_protected(arg) #arg是Test类的对象
  16.         arg.method2     #正确,可以访问同类其他对象的保护方法
  17.     end

  18.     def test_private(arg)    #arg是Test类的对象
  19.         #arg.method3 #错误,不能访问同类其他对象的私有方法
  20.     puts "don't call obj's private method"
  21.     end
  22. end

  23. obj1 = Test.new
  24. obj2 = Test.new
  25. obj1.test_protected(obj2)
  26. class Test
  27.   def method2
  28.     puts "This is a new protected method1"
  29.   end
  30. end

  31. #
  32. obj1.test_protected(obj2)

Ruby可以动态修改类的存取类型,重新修改方法,非常灵活。

 

阅读(545) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~