长牛仔裙怎么搭配:动态语言ruby、groovy、python基本语法复习1
来源:百度文库 编辑:九乡新闻网 时间:2024/05/02 11:52:23
动态语言ruby、groovy、python基本语法复习1
- 博客分类:
- Ruby on Rails
动态语言的丰盛大餐啊,不容错过,下面来简单的复习一下这三门语言。。。
ruby
Ruby代码- # To change this template, choose Tools | Templates
- # and open the template in the editor.
- puts "Hello World"
- print 6/2
- print 'hello'
- puts 'hello'\
- 'world'
- a=1
- b=1.0
- c=1.0
- d=1.0
- e=c
- puts(a==b)#值相等
- puts(a.eql?(b)) #值相等,类型相等
- puts(c.equal?(d))#值相等,内存地址相等
- puts(c.equal?(e))
- puts("abd" <=> "acd") #-1
- puts((0..5) === 10) #false
- puts((0..5) === 3.2) #true
- x=3
- case x
- when 1..2
- print "x=",x,",在1..2中"
- when 4..9,0
- print "x=",x,",在4..9,0中"
- else
- print "x=",x,",其它可能"
- end
- #x=3,其它可能
- a=1
- while( a < 10 )
- print(a," ")
- a=a+1
- end
- b=1
- until( b >= 10 )
- print(b," ")
- b=b+1
- end
- #1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
- 3.times{print "hi"}
- 1.upto(9){|i| print i if i<7}
- 9.downto(1){|i| print i if i<7}
- (1..9).each{|i| print i if i<7}
- 0.step(11,3){|i| print i}
- #hihihi1234566543211234560369
- a=5
- b="hhhh"
- print("a is ",a,"\n") #a is 5
- puts("a is #{a}") #a is 5
- puts('a is #{a}') #a is #{a}
- #ruby支持缺省参数
- def sum(a,b=5)
- a+b
- end
- puts sum(3,6) #输出结果为:9
- puts sum(3)#输出结果为8
- #ruby支持可变参数
- def sum(*num)
- numSum = 0
- num.each{|i| numSum += i}
- return numSum
- end
- puts sum() #输出结果为0
- puts sum(3,6)#输出结果为9
- puts sum(1,2,3,4,5,6,7,8,9)#输出结果为45
- #ruby中如果一个类里有2个同名方法,总是后面的一个被执行
- #实例变量:每个实例独享,变量名用@开头
- #类变量:所有实例共享,变量名用@@开头,类似java里的static变量,但是在使用前必须要初始化。
- #定义类方法 如果在外部调用一个类里的常量,需要用到域作用符号"::"
- class StudentClass
- end
- def StudentClass.student_count
- puts "aaa"
- end
- #ruby里的单例方法:给具体的某个实例对象添加方法,这个方法只属于这个实例对象的。这样的方法叫单例方法
- #定义单例方法,首先要生成一个实例对象,其次要在方法名前加上一个对象名和一个点号(.)
- class Person
- def talk
- puts "hi!"
- end
- end
- p1 = Person.new
- p2 = Person.new
- def p2.talk #定义单例方法p2.talk
- puts "Here is p2."
- end
- def p2.laugh
- puts "ha,ha,ha..."
- end
- p1.talk
- p2.talk
- p2.laugh
- #hi!
- #Here is p2.
- #ha,ha,ha...
- #访问控制
- #public , protected, private
- #public 方法,可以被定义它的类和其子类访问,可以被类和其子类的实例对象调用
- #protected 方法,可以被定义它的类和其子类访问,不能被类和其子类的实例对象调用,但是 可以在类和其子类中制定给实例对象
- #private 方法,可以被定义它的类和其子类访问,不能被类和其子类的实例对象调用,私有方法不能指定对象
- class Person
- public
- def talk
- puts "public:talk"
- end
- def speak
- "protected:speak"
- end
- def laugh
- "private:laugh"
- end
- protected :speak
- private :laugh
- def useLaughTest(another)
- puts another.laugh #这里错误,私有方法不能指定对象
- end
- def useSpeakTest(another)
- puts another.speak #这里可以,,protected方法可以指定对象
- end
- end
- class Student < Person
- def useLaugh
- puts laugh
- end
- def useSpeak
- puts speak
- end
- end
- puts '----------1'
- p1 = Person.new
- p1.talk
- #p1.speak #实例对象不能访问protected方法
- #p1.laugh #实例对象不能访问private方法
- puts '----------2'
- p2 = Student.new
- p2.useLaugh
- puts '----------3'
- p2.useSpeak
groovy
Groovy代码- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package javaapplication1
- /**
- *
- * @author zsbz
- */
- x = 1
- println x
- x = new java.util.Date()
- println x
- x = -3.1499392
- println x
- x = false
- println x
- x = "Hi"
- println x
- myList = [1776, -1, 33, 99, 0, 928734928763]
- println myList[0]
- println myList.size()
- scores = [ "Brett":100, "Pete":"Did not finish", "Andrew":86.87934 ]
- println scores["Pete"]
- println scores.Pete
- scores["Pete"] = 3
- println scores.Pete
- amPM = Calendar.getInstance().get(Calendar.AM_PM)
- if (amPM == Calendar.AM)
- {
- println("Good morning")
- } else {
- println("Good evening")
- }
- square = { it * it }
- println(square(9))
- [ 1, 2, 3, 4 ].collect(square)
- printMapClosure = { key, value -> println key + "=" + value }
- [ "yue" : "wu", "lane" : "burks", "sudha" : "saseethiaseeleethialeselan"].each(printMapClosure)
- fullString = ""
- orderParts = ["BUY", 200, "Hot Dogs", "1"]
- orderParts.each {
- fullString += it + " "
- }
- println fullString
- myMap = ["asdf": 1 , "qwer" : 2, "sdfg" : 10]
- result = 0
- myMap.keySet().each( { result+= myMap[it] } )
- println result
- class Class1 {
- def closure = {
- println this.class.name
- println delegate.class.name
- def nestedClos = {
- println owner.class.name
- }
- nestedClos()
- }
- }
- def clos = new Class1().closure
- clos.delegate = this
- clos()
- /* prints:
- Class1
- Script1
- Class1$_closure1 */
- def list = ['a','b','c','d']
- def newList = []
- list.collect( newList ) {
- it.toUpperCase()
- }
- println newList // ["A", "B", "C", "D"]
- list = ['a','b','c','d']
- newList = []
- clos = { it.toUpperCase() }
- list.collect( newList, clos )
- assert newList == ["A", "B", "C", "D"]
- class Book {
- private String title
- Book (String theTitle) {
- title = theTitle
- }
- String getTitle(){
- return title
- }
- }
- class SomeClass {
- public fieldWithModifier
- String typedField
- def untypedField
- protected field1, field2, field3
- private assignedField = new Date()
- static classField
- public static final String CONSTA = 'a', CONSTB = 'b'
- def someMethod(){
- def localUntypedMethodVar = 1
- int localTypedMethodVar = 1
- def localVarWithoutAssignment, andAnotherOne
- }
- }
- def localvar = 1
- boundvar1 = 1
- def someMethod(){
- localMethodVar = 1
- boundvar2 = 1
- }
- class Counter {
- public count = 0
- }
- def counter = new Counter()
- counter.count = 1
- assert counter.count == 1
- def fieldName = 'count'
- counter[fieldName] = 2
- assert counter['count'] == 2
python
Python代码- import string
- __author__ = "jnotnull"
- __date__ = "$2009-7-14 9:35:19$"
- #coding:utf-8
- print 'hello world'
- print('hello world 我是jnotnull')
- i = 11 #整数类型
- d = 1.5 #浮点数
- str = 'abc' #字符串
- a = 'a' #单个字符
- flag1 = True #bool类型
- flag2 = False #bool类型
- #下面分别是乘法,除法和求余运算
- #print 可以打印多个参数,每个参数中用逗号隔开。
- print i, i * 5, i / 5, i % 2
- print i * d #整数与浮点数相乘
- print str + a #字符串的连接
- s = '100'
- s1 = '1.99'
- print int(s) #类型转换
- print float(s1) #类型转换
- string.atoi(s) #解析整数
- string.atof(s1) #解释浮点数
- arr = (1, 2, 3) #元组,用小(圆)括号
- list = [4, 5, 6] #列表,用中(方)括号
- dict = {} #词典,用大括号,一个空的词典
- dict1 = {1:'a', 2:'b'} #初始化,key是1,value是'a';key 是2,value是'b'
- print arr[0]
- print list[0]
- print dict1
- a = 1
- if a == 1: #注意后面有一个冒号。其中“==”是相等判断
- print 1 #注意print 函数之前有一个tab键,这就是python的强制缩进
- else: #注意else后面的冒号
- print 0 #注意缩进
- if (a == 1): #可以添加园括号
- print 1
- else:
- print 0
- a = 1
- b = 0
- if a == 1 and b == 1: #and 是逻辑“与”运算,自然“or”就是逻辑“或”运算
- print 1
- else:
- print 0
- b = 0
- if a == 0:
- print i
- i -= 1 #注意python不支持i--,i++,--i,++i之类的运算
- elif b == 0:
- print i
- #fun1的函数体为空
- #需要使用pass语句占位,因为函数体至少要有一个句
- #对编写框架程序有用处
- def fun1():
- pass
- #一个最简单的函数,输入一个数,返回这个数的两倍
- def fun2(i):
- return i * 2
- #返回多个值,返回值是一个元组
- def fun3(i):
- return i * 2, i / 2
- #重载,支持不同的参数类型
- def fun4(x):
- import types #引入一个库,可以判断变量的类型
- if type(x) is types.IntType:#判断是否int 类型
- return 2 * x
- if type(x) is types.StringType:#是否string类型
- return x + x
- print 'fun2:', fun2(1)
- print 'fun3:', fun3(4)
- print 'fun4:', fun4(10)
- print 'fun4:', fun4('abc')
- #建立一个类,类名是A,注意A后面有一个冒号
- class A:
- count = 0
- def __init__(self, name): #构造函数,传入参数是name;
- self.name = name #self类似java里面this关键字
- def setName(self, name): #A的一个成员函数
- self.name = name
- def getName(self):
- return self.name
- #__name__是一个系统变量
- #当您直接运行模块,__name__ 的值是 __main__;
- #当您把该文件作为一个导入模块,__name__ 就是其他值
- #这样方便测试
- if __name__ == "__main__":
- #初始化一个对象A
- a = A('poson')
- print a.getName()
- class HttpBase:
- def get(self):
- psss
- class Http1(HttpBase):
- def get(self):
- print 'http1'
- class Http2(HttpBase):
- def get(self):
- print 'http2'
- class Base:
- def __init__(self):
- self.httpobj = None
- def http(self):
- self.httpobj.get()
- def compute(self):
- self.http()
- self.show()
- #虚函数
- def show(self):
- pass
- def notify(self, k):
- print 'notify', k
- #桥接模式,通过A,B 关联不同的http1和http2
- class BaseA(Base):
- def __init__(self):
- self.httpobj = Http1()
- def notify(self, k):
- print 'A notify', k
- def show(self):
- print 'show a'
- class BaseB(Base):
- def __init__(self):
- self.httpobj = Http2()
- def notify(self, k):
- print 'B notify', k
- def show(self):
- print 'show b'
- #观测者模式
- class Observer:
- def __init__(self):
- self.listOB = []
- def register(self, obj):
- self.listOB.append(obj)
- def notify(self):
- for obj in self.listOB:
- obj.notify(len(self.listOB))
- #适配器模式
- class B1:
- def http(self):
- BaseB().http()
- #工厂模式
- class Factory:
- def CreateA(self):
- return BaseA()
- def CreateB(self):
- return BaseB()
- #单例模式
- class Logger(object):
- log = None
- @staticmethod
- def new():
- import threading
- #线程安全
- mylock = threading.RLock()
- mylock.acquire()
- if not Logger.log:
- Logger.log = Logger()
- mylock.release()
- return Logger.log
- def write(self, v):
- print 'Logger ', v
- if __name__ == "__main__":
- a = Factory().CreateA()
- b = Factory().CreateB()
- objS = Observer()
- objS.register(a)
- objS.register(b)
- a.compute()
- b.compute()
- objS.notify()
- b1 = B1()
- b1.http()
- Logger.new().log.write('v')
参考资料http://poson.iteye.com
http://openmouse.iteye.com
动态语言ruby、groovy、python基本语法复习1
每个程序员都应该学习使用Python或Ruby
基本语法
精彩语法复习讲义(1)o
精彩语法复习讲义(11)1
精彩语法复习讲义(10)1
语文语法知识复习(词性知识)1
精彩语法复习讲义(1)
.NET程序员新方向 Ruby核心语法入门
[Python]python和C语言分别实现快速排序
HTML语言语法大全
Python编程语言入门学习-编程语言-开发语言
精彩语法复习讲义
初中英语语法复习汇总表
《牛津小学英语》语法复习
现代汉语语法复习
编程中国?>>?Python成为2010年度语言
embed基本语法
Fortran95基本语法
2011中考英语备考:初中语法复习(1)5
[Python]Python完全新手教程 -- 1
马克思主义原理基本概论考试复习1
瑜伽基本体位全--动态图1
西方语言语法的 发展