长牛仔裙怎么搭配:动态语言ruby、groovy、python基本语法复习1

来源:百度文库 编辑:九乡新闻网 时间:2024/05/02 11:52:23

动态语言ruby、groovy、python基本语法复习1

    博客分类:
  • Ruby on Rails
RubyPythonGroovyD语言C

动态语言的丰盛大餐啊,不容错过,下面来简单的复习一下这三门语言。。。

ruby

Ruby代码 
  1. # To change this template, choose Tools | Templates  
  2. # and open the template in the editor.  
  3.   
  4. puts "Hello World"  
  5. print 6/2  
  6. print 'hello'  
  7. puts 'hello'\  
  8.   'world'  
  9.   
  10. a=1  
  11. b=1.0  
  12. c=1.0  
  13. d=1.0  
  14. e=c  
  15. puts(a==b)#值相等  
  16. puts(a.eql?(b)) #值相等,类型相等  
  17. puts(c.equal?(d))#值相等,内存地址相等  
  18. puts(c.equal?(e))  
  19.   
  20. puts("abd" <=> "acd") #-1  
  21. puts((0..5) === 10) #false  
  22. puts((0..5) === 3.2) #true  
  23.   
  24.   
  25. x=3  
  26. case x  
  27. when 1..2  
  28.   print "x=",x,",在1..2中"  
  29. when 4..9,0  
  30.   print "x=",x,",在4..9,0中"  
  31. else  
  32.   print "x=",x,",其它可能"  
  33. end  
  34. #x=3,其它可能  
  35.   
  36. a=1  
  37. while( a < 10 )  
  38.   print(a," ")  
  39.   a=a+1  
  40. end  
  41.   
  42. b=1  
  43. until( b >= 10 )  
  44.   print(b," ")  
  45.   b=b+1  
  46. end  
  47. #1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9  
  48.   
  49. 3.times{print "hi"}  
  50. 1.upto(9){|i| print i if i<7}  
  51. 9.downto(1){|i| print i if i<7}  
  52. (1..9).each{|i| print i if i<7}  
  53. 0.step(11,3){|i| print i}  
  54. #hihihi1234566543211234560369  
  55.   
  56. a=5  
  57. b="hhhh"  
  58. print("a is ",a,"\n")    #a is 5  
  59. puts("a is #{a}")    #a is 5  
  60. puts('a is #{a}') #a is #{a}  
  61.   
  62. #ruby支持缺省参数  
  63. def sum(a,b=5)  
  64.   a+b  
  65. end  
  66. puts sum(3,6) #输出结果为:9  
  67. puts sum(3)#输出结果为8  
  68.   
  69. #ruby支持可变参数  
  70. def sum(*num)  
  71.   numSum = 0  
  72.   num.each{|i| numSum += i}  
  73.   return numSum  
  74. end  
  75.   
  76. puts sum() #输出结果为0  
  77. puts sum(3,6)#输出结果为9  
  78. puts sum(1,2,3,4,5,6,7,8,9)#输出结果为45  
  79.   
  80. #ruby中如果一个类里有2个同名方法,总是后面的一个被执行  
  81.   
  82. #实例变量:每个实例独享,变量名用@开头  
  83. #类变量:所有实例共享,变量名用@@开头,类似java里的static变量,但是在使用前必须要初始化。  
  84. #定义类方法 如果在外部调用一个类里的常量,需要用到域作用符号"::"  
  85. class StudentClass  
  86.   
  87. end  
  88. def StudentClass.student_count  
  89.   puts "aaa"  
  90. end  
  91.   
  92. #ruby里的单例方法:给具体的某个实例对象添加方法,这个方法只属于这个实例对象的。这样的方法叫单例方法  
  93. #定义单例方法,首先要生成一个实例对象,其次要在方法名前加上一个对象名和一个点号(.)  
  94. class Person  
  95.   def talk  
  96.     puts "hi!"  
  97.   end  
  98. end  
  99.   
  100. p1 = Person.new  
  101. p2 = Person.new  
  102.   
  103. def p2.talk #定义单例方法p2.talk  
  104.   puts "Here is p2."  
  105. end  
  106. def p2.laugh  
  107.   puts "ha,ha,ha..."  
  108. end  
  109.   
  110. p1.talk  
  111. p2.talk  
  112. p2.laugh  
  113.   
  114. #hi!  
  115. #Here is p2.  
  116. #ha,ha,ha...  
  117.   
  118. #访问控制  
  119. #public , protected, private  
  120. #public 方法,可以被定义它的类和其子类访问,可以被类和其子类的实例对象调用  
  121. #protected 方法,可以被定义它的类和其子类访问,不能被类和其子类的实例对象调用,但是 可以在类和其子类中制定给实例对象  
  122. #private 方法,可以被定义它的类和其子类访问,不能被类和其子类的实例对象调用,私有方法不能指定对象  
  123.   
  124. class Person  
  125.   public  
  126.   def talk  
  127.     puts "public:talk"  
  128.   end  
  129.   def speak  
  130.     "protected:speak"  
  131.   end  
  132.   def laugh  
  133.     "private:laugh"  
  134.   end  
  135.   protected :speak  
  136.   private :laugh  
  137.   
  138.   def useLaughTest(another)  
  139.     puts another.laugh #这里错误,私有方法不能指定对象  
  140.   end  
  141.   
  142.   def useSpeakTest(another)  
  143.     puts another.speak  #这里可以,,protected方法可以指定对象  
  144.   end  
  145. end  
  146.   
  147. class Student < Person  
  148.   def useLaugh  
  149.     puts laugh  
  150.   end  
  151.   def useSpeak  
  152.     puts speak  
  153.   end  
  154. end  
  155. puts '----------1'  
  156. p1 = Person.new  
  157. p1.talk  
  158. #p1.speak #实例对象不能访问protected方法  
  159. #p1.laugh #实例对象不能访问private方法  
  160. puts '----------2'  
  161. p2 = Student.new  
  162. p2.useLaugh  
  163. puts '----------3'  
  164. p2.useSpeak  

 

groovy

Groovy代码 
  1. /*  
  2.  * To change this template, choose Tools | Templates  
  3.  * and open the template in the editor.  
  4.  */  
  5.   
  6. package javaapplication1  
  7.   
  8. /**  
  9.  *  
  10.  * @author zsbz  
  11.  */  
  12. x = 1  
  13. println x  
  14. x = new java.util.Date()  
  15. println x  
  16. x = -3.1499392  
  17. println x  
  18. x = false  
  19. println x  
  20. x = "Hi"  
  21. println x  
  22.   
  23. myList = [1776, -1, 33, 99, 0, 928734928763]  
  24. println myList[0]  
  25. println myList.size()  
  26.   
  27. scores = [ "Brett":100, "Pete":"Did not finish", "Andrew":86.87934 ]  
  28. println scores["Pete"]  
  29. println scores.Pete   
  30. scores["Pete"] = 3  
  31. println scores.Pete  
  32.   
  33. amPM = Calendar.getInstance().get(Calendar.AM_PM)  
  34. if (amPM == Calendar.AM)  
  35. {  
  36.     println("Good morning")  
  37. } else {  
  38.     println("Good evening")  
  39. }  
  40.   
  41. square = { it * it }  
  42. println(square(9))  
  43. [ 1, 2, 3, 4 ].collect(square)  
  44.   
  45. printMapClosure = { key, value -> println key + "=" + value }  
  46. [ "yue" : "wu", "lane" : "burks", "sudha" : "saseethiaseeleethialeselan"].each(printMapClosure)  
  47.   
  48. fullString = ""  
  49. orderParts = ["BUY", 200, "Hot Dogs", "1"]  
  50. orderParts.each {  
  51.     fullString += it + " "  
  52. }  
  53. println fullString  
  54.   
  55. myMap = ["asdf": 1 , "qwer" : 2, "sdfg" : 10]  
  56. result = 0  
  57. myMap.keySet().each( { result+= myMap[it] } )  
  58. println result  
  59.   
  60. class Class1 {  
  61.     def closure = {  
  62.         println this.class.name  
  63.         println delegate.class.name  
  64.         def nestedClos = {  
  65.             println owner.class.name  
  66.         }  
  67.         nestedClos()  
  68.     }  
  69. }  
  70. def clos = new Class1().closure  
  71. clos.delegate = this  
  72. clos()  
  73. /* prints:  
  74. Class1  
  75. Script1  
  76. Class1$_closure1 */  
  77.   
  78. def list = ['a','b','c','d']  
  79. def newList = []  
  80. list.collect( newList ) {  
  81.     it.toUpperCase()  
  82. }  
  83. println newList // ["A", "B", "C", "D"]  
  84.   
  85. list = ['a','b','c','d']  
  86. newList = []  
  87. clos = { it.toUpperCase() }  
  88. list.collect( newList, clos )  
  89. assert newList == ["A", "B", "C", "D"]  
  90.   
  91. class Book {  
  92.     private String title  
  93.     Book (String theTitle) {  
  94.         title = theTitle  
  95.     }  
  96.     String getTitle(){  
  97.         return title  
  98.     }  
  99. }  
  100.   
  101. class SomeClass {  
  102.     public fieldWithModifier  
  103.     String typedField  
  104.     def untypedField  
  105.     protected field1, field2, field3  
  106.     private assignedField = new Date()  
  107.     static classField  
  108.     public static final String CONSTA = 'a', CONSTB = 'b'  
  109.     def someMethod(){  
  110.         def localUntypedMethodVar = 1  
  111.         int localTypedMethodVar = 1  
  112.         def localVarWithoutAssignment, andAnotherOne  
  113.     }  
  114. }  
  115. def localvar = 1  
  116. boundvar1 = 1  
  117. def someMethod(){  
  118.     localMethodVar = 1  
  119.     boundvar2 = 1  
  120. }  
  121.   
  122. class Counter {  
  123.     public count = 0  
  124. }  
  125. def counter = new Counter()  
  126. counter.count = 1  
  127. assert counter.count == 1  
  128. def fieldName = 'count'  
  129. counter[fieldName] = 2  
  130. assert counter['count'] == 2  

 

 

python

Python代码 
  1. import string  
  2. __author__ = "jnotnull"  
  3. __date__ = "$2009-7-14 9:35:19$"  
  4. #coding:utf-8  
  5. print 'hello world'  
  6. print('hello world 我是jnotnull')  
  7.   
  8. i = 11   #整数类型  
  9. d = 1.5 #浮点数  
  10. str = 'abc'  #字符串  
  11. a = 'a'      #单个字符  
  12. flag1 = True   #bool类型  
  13. flag2 = False  #bool类型  
  14.   
  15. #下面分别是乘法,除法和求余运算  
  16. #print 可以打印多个参数,每个参数中用逗号隔开。  
  17. print i, i * 5, i / 5, i % 2  
  18. print i * d     #整数与浮点数相乘  
  19. print str + a   #字符串的连接  
  20.   
  21. s = '100'  
  22. s1 = '1.99'  
  23. print int(s)   #类型转换  
  24. print float(s1) #类型转换  
  25. string.atoi(s)   #解析整数  
  26. string.atof(s1)  #解释浮点数  
  27.   
  28. arr = (1, 2, 3)      #元组,用小(圆)括号  
  29. list = [4, 5, 6]     #列表,用中(方)括号  
  30. dict = {}            #词典,用大括号,一个空的词典  
  31. dict1 = {1:'a', 2:'b'}  #初始化,key是1,value是'a';key 是2,value是'b'  
  32.   
  33. print arr[0]  
  34. print list[0]  
  35. print dict1  
  36.   
  37. a = 1  
  38. if a == 1:         #注意后面有一个冒号。其中“==”是相等判断  
  39.     print 1       #注意print 函数之前有一个tab键,这就是python的强制缩进  
  40. else:         #注意else后面的冒号  
  41.     print 0       #注意缩进  
  42.   
  43. if (a == 1):      #可以添加园括号  
  44.     print 1  
  45. else:  
  46.     print 0  
  47.   
  48. a = 1  
  49. b = 0  
  50. if a == 1 and b == 1:   #and 是逻辑“与”运算,自然“or”就是逻辑“或”运算  
  51.     print 1  
  52. else:  
  53.     print 0  
  54.   
  55. b = 0  
  56. if a == 0:  
  57.     print i  
  58.     i -= 1       #注意python不支持i--,i++,--i,++i之类的运算  
  59. elif b == 0:  
  60.     print  i  
  61.   
  62. #fun1的函数体为空  
  63. #需要使用pass语句占位,因为函数体至少要有一个句  
  64. #对编写框架程序有用处  
  65. def fun1():  
  66.     pass  
  67.   
  68. #一个最简单的函数,输入一个数,返回这个数的两倍  
  69. def fun2(i):  
  70.     return i * 2  
  71.   
  72. #返回多个值,返回值是一个元组  
  73. def fun3(i):  
  74.     return i * 2, i / 2  
  75.   
  76. #重载,支持不同的参数类型  
  77. def fun4(x):  
  78.     import   types   #引入一个库,可以判断变量的类型  
  79.     if type(x)   is   types.IntType:#判断是否int   类型  
  80.         return 2 * x  
  81.     if type(x)   is   types.StringType:#是否string类型  
  82.         return x + x  
  83.   
  84.   
  85. print 'fun2:', fun2(1)  
  86. print 'fun3:', fun3(4)  
  87.   
  88. print 'fun4:', fun4(10)  
  89. print 'fun4:', fun4('abc')  
  90.   
  91. #建立一个类,类名是A,注意A后面有一个冒号  
  92. class A:  
  93.     count = 0  
  94.     def __init__(self, name):   #构造函数,传入参数是name;  
  95.         self.name = name        #self类似java里面this关键字  
  96.   
  97.     def setName(self, name):    #A的一个成员函数  
  98.         self.name = name  
  99.     def getName(self):  
  100.         return self.name  
  101.   
  102. #__name__是一个系统变量  
  103. #当您直接运行模块,__name__ 的值是 __main__;  
  104. #当您把该文件作为一个导入模块,__name__ 就是其他值  
  105. #这样方便测试  
  106. if __name__ == "__main__":  
  107.     #初始化一个对象A  
  108.     a = A('poson')  
  109.     print a.getName()  
  110.   
  111. class HttpBase:  
  112.     def get(self):  
  113.         psss  
  114. class Http1(HttpBase):  
  115.     def get(self):  
  116.         print 'http1'  
  117. class Http2(HttpBase):  
  118.     def get(self):  
  119.         print 'http2'  
  120.   
  121.   
  122. class Base:  
  123.     def __init__(self):  
  124.         self.httpobj = None  
  125.     def http(self):  
  126.         self.httpobj.get()  
  127.     def compute(self):  
  128.         self.http()  
  129.         self.show()  
  130.     #虚函数  
  131.     def show(self):  
  132.         pass  
  133.     def notify(self, k):  
  134.         print 'notify', k  
  135.   
  136.   
  137. #桥接模式,通过A,B 关联不同的http1和http2  
  138. class BaseA(Base):  
  139.     def __init__(self):  
  140.         self.httpobj = Http1()  
  141.     def notify(self, k):  
  142.         print 'A notify', k  
  143.     def show(self):  
  144.         print 'show a'  
  145.   
  146. class BaseB(Base):  
  147.     def __init__(self):  
  148.         self.httpobj = Http2()  
  149.     def notify(self, k):  
  150.         print 'B notify', k  
  151.     def show(self):  
  152.         print 'show b'  
  153.   
  154. #观测者模式  
  155. class Observer:  
  156.     def __init__(self):  
  157.         self.listOB = []  
  158.     def register(self, obj):  
  159.         self.listOB.append(obj)  
  160.     def notify(self):  
  161.         for obj in self.listOB:  
  162.             obj.notify(len(self.listOB))  
  163.   
  164. #适配器模式  
  165. class B1:  
  166.     def http(self):  
  167.         BaseB().http()  
  168. #工厂模式  
  169. class Factory:  
  170.     def CreateA(self):  
  171.         return BaseA()  
  172.     def CreateB(self):  
  173.         return BaseB()  
  174.   
  175.   
  176. #单例模式  
  177. class Logger(object):  
  178.     log = None  
  179.     @staticmethod  
  180.     def new():  
  181.         import threading  
  182.         #线程安全  
  183.         mylock = threading.RLock()  
  184.         mylock.acquire()  
  185.         if not Logger.log:  
  186.             Logger.log = Logger()  
  187.         mylock.release()  
  188.   
  189.         return Logger.log  
  190.     def write(self, v):  
  191.         print 'Logger ', v  
  192.   
  193. if __name__ == "__main__":  
  194.     a = Factory().CreateA()  
  195.     b = Factory().CreateB()  
  196.   
  197.     objS = Observer()  
  198.     objS.register(a)  
  199.     objS.register(b)  
  200.   
  201.     a.compute()  
  202.     b.compute()  
  203.     objS.notify()  
  204.   
  205.     b1 = B1()  
  206.     b1.http()  
  207.   
  208.     Logger.new().log.write('v')    

 

 

参考资料http://poson.iteye.com

http://openmouse.iteye.com