動(dòng)態(tài)語言的豐盛大餐啊,不容錯(cuò)過,下面來簡單的復(fù)習(xí)一下這三門語言。。。
ruby
-
-
-
- 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")
- puts((0..5) === 10)
- puts((0..5) === 3.2)
-
-
- 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
-
-
- a=1
- while( a < 10 )
- print(a," ")
- a=a+1
- end
-
- b=1
- until( b >= 10 )
- print(b," ")
- b=b+1
- end
-
-
- 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}
-
-
- a=5
- b="hhhh"
- print("a is ",a,"\n")
- puts("a is #{a}") #a is 5
- puts('a is #{a}') #a is #{a}
-
-
- def sum(a,b=5)
- a+b
- end
- puts sum(3,6)
- puts sum(3)
-
-
- def sum(*num)
- numSum = 0
- num.each{|i| numSum += i}
- return numSum
- end
-
- puts sum()
- puts sum(3,6)
- puts sum(1,2,3,4,5,6,7,8,9)
-
-
-
-
-
-
- class StudentClass
-
- end
- def StudentClass.student_count
- puts "aaa"
- end
-
-
-
- class Person
- def talk
- puts "hi!"
- end
- end
-
- p1 = Person.new
- p2 = Person.new
-
- def p2.talk
- puts "Here is p2."
- end
- def p2.laugh
- puts "ha,ha,ha..."
- end
-
- p1.talk
- p2.talk
- p2.laugh
-
-
-
-
-
-
-
-
-
-
-
- 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
- end
- end
-
- class Student < Person
- def useLaugh
- puts laugh
- end
- def useSpeak
- puts speak
- end
- end
- puts '----------1'
- p1 = Person.new
- p1.talk
-
-
- puts '----------2'
- p2 = Student.new
- p2.useLaugh
- puts '----------3'
- p2.useSpeak
# 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))#值相等,內(nèi)存地址相等
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支持缺省參數(shù)
def sum(a,b=5)
a+b
end
puts sum(3,6) #輸出結(jié)果為:9
puts sum(3)#輸出結(jié)果為8
#ruby支持可變參數(shù)
def sum(*num)
numSum = 0
num.each{|i| numSum += i}
return numSum
end
puts sum() #輸出結(jié)果為0
puts sum(3,6)#輸出結(jié)果為9
puts sum(1,2,3,4,5,6,7,8,9)#輸出結(jié)果為45
#ruby中如果一個(gè)類里有2個(gè)同名方法,總是后面的一個(gè)被執(zhí)行
#實(shí)例變量:每個(gè)實(shí)例獨(dú)享,變量名用@開頭
#類變量:所有實(shí)例共享,變量名用@@開頭,類似java里的static變量,但是在使用前必須要初始化。
#定義類方法 如果在外部調(diào)用一個(gè)類里的常量,需要用到域作用符號"::"
class StudentClass
end
def StudentClass.student_count
puts "aaa"
end
#ruby里的單例方法:給具體的某個(gè)實(shí)例對象添加方法,這個(gè)方法只屬于這個(gè)實(shí)例對象的。這樣的方法叫單例方法
#定義單例方法,首先要生成一個(gè)實(shí)例對象,其次要在方法名前加上一個(gè)對象名和一個(gè)點(diǎn)號(.)
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 方法,可以被定義它的類和其子類訪問,可以被類和其子類的實(shí)例對象調(diào)用
#protected 方法,可以被定義它的類和其子類訪問,不能被類和其子類的實(shí)例對象調(diào)用,但是 可以在類和其子類中制定給實(shí)例對象
#private 方法,可以被定義它的類和其子類訪問,不能被類和其子類的實(shí)例對象調(diào)用,私有方法不能指定對象
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 #這里錯(cuò)誤,私有方法不能指定對象
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 #實(shí)例對象不能訪問protected方法
#p1.laugh #實(shí)例對象不能訪問private方法
puts '----------2'
p2 = Student.new
p2.useLaugh
puts '----------3'
p2.useSpeak
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
/*
* 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
- import string
- __author__ = "jnotnull"
- __date__ = "$2009-7-14 9:35:19$"
-
- print 'hello world'
- print('hello world 我是jnotnull')
-
- i = 11
- d = 1.5
- str = 'abc'
- a = 'a'
- flag1 = True
- flag2 = False
-
-
-
- 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'}
-
- print arr[0]
- print list[0]
- print dict1
-
- a = 1
- if a == 1:
- print 1
- else:
- print 0
-
- if (a == 1):
- print 1
- else:
- print 0
-
- a = 1
- b = 0
- if a == 1 and b == 1:
- print 1
- else:
- print 0
-
- b = 0
- if a == 0:
- print i
- i -= 1
- elif b == 0:
- print i
-
-
-
-
- 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:
- return 2 * x
- if type(x) is types.StringType:
- return x + x
-
-
- print 'fun2:', fun2(1)
- print 'fun3:', fun3(4)
-
- print 'fun4:', fun4(10)
- print 'fun4:', fun4('abc')
-
-
- class A:
- count = 0
- def __init__(self, name):
- self.name = name
-
- def setName(self, name):
- self.name = name
- def getName(self):
- return self.name
-
-
-
-
-
- if __name__ == "__main__":
-
- 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
-
-
-
- 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')
import string
__author__ = "jnotnull"
__date__ = "$2009-7-14 9:35:19$"
#coding:utf-8
print 'hello world'
print('hello world 我是jnotnull')
i = 11 #整數(shù)類型
d = 1.5 #浮點(diǎn)數(shù)
str = 'abc' #字符串
a = 'a' #單個(gè)字符
flag1 = True #bool類型
flag2 = False #bool類型
#下面分別是乘法,除法和求余運(yùn)算
#print 可以打印多個(gè)參數(shù),每個(gè)參數(shù)中用逗號隔開。
print i, i * 5, i / 5, i % 2
print i * d #整數(shù)與浮點(diǎn)數(shù)相乘
print str + a #字符串的連接
s = '100'
s1 = '1.99'
print int(s) #類型轉(zhuǎn)換
print float(s1) #類型轉(zhuǎn)換
string.atoi(s) #解析整數(shù)
string.atof(s1) #解釋浮點(diǎn)數(shù)
arr = (1, 2, 3) #元組,用?。▓A)括號
list = [4, 5, 6] #列表,用中(方)括號
dict = {} #詞典,用大括號,一個(gè)空的詞典
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: #注意后面有一個(gè)冒號。其中“==”是相等判斷
print 1 #注意print 函數(shù)之前有一個(gè)tab鍵,這就是python的強(qiáng)制縮進(jìn)
else: #注意else后面的冒號
print 0 #注意縮進(jìn)
if (a == 1): #可以添加園括號
print 1
else:
print 0
a = 1
b = 0
if a == 1 and b == 1: #and 是邏輯“與”運(yùn)算,自然“or”就是邏輯“或”運(yùn)算
print 1
else:
print 0
b = 0
if a == 0:
print i
i -= 1 #注意python不支持i--,i++,--i,++i之類的運(yùn)算
elif b == 0:
print i
#fun1的函數(shù)體為空
#需要使用pass語句占位,因?yàn)楹瘮?shù)體至少要有一個(gè)句
#對編寫框架程序有用處
def fun1():
pass
#一個(gè)最簡單的函數(shù),輸入一個(gè)數(shù),返回這個(gè)數(shù)的兩倍
def fun2(i):
return i * 2
#返回多個(gè)值,返回值是一個(gè)元組
def fun3(i):
return i * 2, i / 2
#重載,支持不同的參數(shù)類型
def fun4(x):
import types #引入一個(gè)庫,可以判斷變量的類型
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')
#建立一個(gè)類,類名是A,注意A后面有一個(gè)冒號
class A:
count = 0
def __init__(self, name): #構(gòu)造函數(shù),傳入?yún)?shù)是name;
self.name = name #self類似java里面this關(guān)鍵字
def setName(self, name): #A的一個(gè)成員函數(shù)
self.name = name
def getName(self):
return self.name
#__name__是一個(gè)系統(tǒng)變量
#當(dāng)您直接運(yùn)行模塊,__name__ 的值是 __main__;
#當(dāng)您把該文件作為一個(gè)導(dǎo)入模塊,__name__ 就是其他值
#這樣方便測試
if __name__ == "__main__":
#初始化一個(gè)對象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()
#虛函數(shù)
def show(self):
pass
def notify(self, k):
print 'notify', k
#橋接模式,通過A,B 關(guān)聯(lián)不同的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.
http://openmouse.
|