一,語句的結(jié)束
- 每一句邏輯行的結(jié)束都是以物理行的結(jié)束為結(jié)束。如果邏輯行想鏈接兩行物理行,請使用“\”,但值得注意的是,他只能用來鏈接代碼而不是能鏈接兩行注釋或字符串,如:
<code>if 1900 < year < 2100 and 1 <= month <= 12 \ and 1 <= day <= 31 and 0 <= hour < 24 \ and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date return 1
- 但是括號內(nèi)的內(nèi)容,不需要使用反斜杠也可以鏈接多行,如:
<code>month_names = ['Januari', 'Februari', 'Maart', # These are the 'April', 'Mei', 'Juni', # Dutch names 'Juli', 'Augustus', 'September', # for the months 'Oktober', 'November', 'December'] # of the year
二,如何定義一個函數(shù)或者方法
use "def" to definition fuction
三,一個*號和兩個的區(qū)別
<code>2*3 表示2乘以3 2**3表示2的立方
四,縮進——代碼格式
java通過括號來界定一段代碼,而python使用縮進做為代碼段的界定。空格和tabs都可以用來作為縮進,但最好不要混用。如:
<code>def perm(l):
# Compute the list of all permutations of l
if len(l) <= 1:
return [l]
r = []
for i in range(len(l)):
s = l[:i] + l[i+1:]
p = perm(s)
for x in p:
r.append(l[i:i+1] + x)
return r
五,字符串連接
用引號擴起來的兩個相鄰字符串,實際意義表示為他們兩相連的那個字符串。且這兩個字符串的引號可以不同,例如:
<code>"hello" 'world' is equivalent to "helloworld".
六,數(shù)據(jù)結(jié)構(gòu)
在python中所有數(shù)據(jù)類型都是對象,比如int、和string。這同java不一樣,java中int是原始本地類型(primitive native types)
6.1 list和tuble的區(qū)別
- list是用方括號括起來的,成員之間通過逗號分割的表示方式。tuble是用小括號(小括號可選)擴起來,成員直接用逗號分割。
- list是可變的,可以進行增刪改,tuble如其名一樣,作為元組他們是不變的
6.2 dictionary
dictionary有點類似java中的map。dictionary的key必須是唯一且不可修改的值,比如string,但其映射的value可以是可變的值,如list,解讀的意思,就是key值必須取基本類型,比如int和string,因為基本類型都是不可變的。dictionary的格式有點像json
6.3 sequence
6.3.1 定義
sequence特指那些具有順序的數(shù)據(jù)類型,所以前面介紹的list、tuple、string都屬于sequence類型
6.3.2 用法
6.3.2.1 索引取值
使用方括號加數(shù)字表示取sequence的具體某位置的值,如:[2]
6.3.2.2 子sequence截取
使用方括號加冒號的方式表示取子sequence,冒號是必須的,兩邊的數(shù)字可選,取值方式為左開右閉,如:[2:3]
<code>值得說明的是,截取的子sequence是一個完全新的對象,所以如果不指定數(shù)字,而直接使用[:]來截取,相當(dāng)于對原sequence復(fù)制了一份新的對象
使用兩個冒號時,第三個數(shù)字指定截取時的步長,如:[2:3:1]
6.4 Set
無序的對象集合,原理和操作方式同java類似
6.5 References
聲明一個變量,并給他賦值。實際上是把對象的引用賦給了這個變量。多一個變量可以指向同一個對象。引用的概念同java類似
七,編程方式
7.1 面向過程編程
python支持面向過程編程風(fēng)格,就像c一樣,定義方法,定義變量。程序的組織方式是通過過程塊來組織
7.2 面向?qū)ο缶幊?/h2>
python同時也支持面向?qū)ο缶幊田L(fēng)格,就像java一樣。類來組織程序塊,類中可以定義函數(shù),變量,類中的函數(shù)叫做方法。類中的變量和方法統(tǒng)稱為類的屬性
屬于每一個實例的變量叫做實例變量
只屬于類的變量叫做類變量
7.2.1 self
類似java中this引用,指代當(dāng)前對象。類中的方法其必須都要有一個參數(shù),這個參數(shù)就是self,用來指代調(diào)用該方法的當(dāng)前對象,當(dāng)然調(diào)用該方法時不用顯示寫出這個參數(shù),python自己提供
7.2.2 類定義
一個簡單的類定義如下:
<code>__author__ = 'vincentc'
class Person :
pass
p = Person()
print(p)
7.2.3 定義類方法示例
<code>__author__ = 'vincentc'
class Person:
def sayHi(self): #每個類方法,都必須定義的默認(rèn)參數(shù),指代調(diào)用該方法的當(dāng)前對象,名字約定俗成為self,最好沿用這個。該方法在調(diào)用時,不用顯示指定該參數(shù),有python默認(rèn)提供
print('Hello,how are you')
p = Person()
p.sayHi()
7.2.4 初始化方法(__init__)
__init__方法用來在創(chuàng)建對象時,初始化一些數(shù)據(jù),同java的構(gòu)造方法類似,示例如下:
<code>__author__ = 'vincentc'
class Person:
def __init__(self,name):
self.name = name
def sayHi(self):
print('Hello,my name is',self.name)
p = Person('Vincent')
p.sayHi()
7.2.5 類變量實例變量以及類方法和實例方法
<code>__author__ = 'vincentc'
class Robot:
"""This is class docString."""
#類變量,只有一份,所有實例都可以訪問,一改全改
population = 0
def __init__(self,name):
"""This is method docString."""
self.name = name
Robot.population +=1
def die(self):
Robot.population -=1
def sayHi(self):
print(self.name)
@classmethod #該標(biāo)注定義類方法
def howMany(cls):
print(cls.population)
droid1 = Robot("R2-D2")
droid1.sayHi() #實例方法的調(diào)用方式
Robot.howMany()#類方法的調(diào)用方式
7.2.6 私有成員
約定任何名稱以一個下劃線開頭的成員,都為私有成員,但僅僅是約定,不是強制。以兩個下劃線開頭的為強制私有成員,如:__privatevar
7.2.7 類繼承
繼承的概念和寫法大致跟java類似,不同的地方有:
- python繼承的父類寫在小括號里,且支持多繼承,用逗號分開
- 子類在初始化時不會像java那樣隱式調(diào)用父類的初始化方法,必須要手動顯示調(diào)用
<code>__author__ = 'vincentc'
class SchoolMember:
'''Represents any school member.'''
def __init__(self, name, age):
self.name = name
self.age = age
print('(Initialized SchoolMember: {0})'.format(self.name))
def tell(self):
'''Tell my details.'''
print('Name:"{0}" Age:"{1}"'.format(self.name, self.age), end=" ")
class Teacher(SchoolMember):
'''Represents a teacher.'''
def __init__(self, name, age, salary):
SchoolMember.__init__(self, name, age)
self.salary = salary
print('(Initialized Teacher: {0})'.format(self.name))
def tell(self):
SchoolMember.tell(self)
print('Salary: "{0:d}"'.format(self.salary))
class Student(SchoolMember):
'''Represents a student.'''
def __init__(self, name, age, marks):
SchoolMember.__init__(self, name, age)
self.marks = marks
print('(Initialized Student: {0})'.format(self.name))
def tell(self):
SchoolMember.tell(self)
print('Marks: "{0:d}"'.format(self.marks))
t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 25, 75)
print() # prints a blank line
members = [t, s]
for member in members:
member.tell() # works for both Teachers and Students
八,docString
docString用來描述一個類、方法、模塊的用途。
8.1 定義
docString必須放在類、函數(shù)(方法)、模塊的第一個邏輯行。其余公約如下:
- 第一行首字母大寫,并且以點號結(jié)尾
- 第二行為空行
- 第三行為具體明細(xì)解釋
<code>__author__ = 'vincentc'
def printMax(x,y):
'''Prints the maximum of two numbers.
the two values must be integers.'''
x = int(x)
y = int(y)
if x>y:
print(x,'is maximum')
else:
print(y,'is maximum')
printMax(3,5)
print(printMax.__doc__)
8.2 使用
- 用方法、類、模塊名,調(diào)用該變量,如:
printMax.__doc__ - 用help方法自動調(diào)用,如:
help(printMax)
九,輸入輸出
9.1 input&print
input可以用來接受用戶的輸入。print用來打印輸出
9.2 讀寫文件
有多種模式可以打開文件,以讀的方式,寫的方式等,示例如下:
<code>poem = '''sfsdfsdfsdfsdfsdfsdfs'''
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
f = open('poem.txt') # if no mode is specified, 'r'ead mode is assumed by default
while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print(line, end='')
f.close() # close the file
9.3 Pickle
將python對象持久化到文件,并可從文件中提取出來,同java的序列化和反序列化類似,示例:
<code>__author__ = 'vincentc' import pickle # the name of the file where we will store the object # shoplistfile = 'shoplist.data' # the list of things to buy # shoplist = ['apple', 'mango', 'carrot'] # Write to the file # f = open(shoplistfile, 'wb') pickle.dump(shoplist, f) # dump the object to a file f.close() del shoplist # destroy the shoplist variable # Read back from the storage # f = open(shoplistfile, 'rb') storedlist = pickle.load(f) # load the object from the file print(storedlist)
9.4 Unicode
如何以utf-8的方式讀寫文件,示例(注:第一行的注釋也是必須的):
<code># encoding=utf-8
f = open("abc.txt", "wt", encoding="utf-8")
f.write("Imagine non-English language here")
f.close()
text = open("abc.txt", encoding="utf-8").read()
十, Exceptions
10.1 處理異常
句型為:
<code>try:
....
except [exceptionName]:
....
else:
...
finally:
...
說明,except語句可以為多個同java類似,exceptionName為可選,如果不寫表示攔截所有的Exception,else語句表示沒有出現(xiàn)異常時執(zhí)行的語句。finally表示無論是否有異常都會執(zhí)行的語句,可以用來關(guān)閉文件,或網(wǎng)絡(luò)鏈接等資源。當(dāng)然如果出現(xiàn)異常將不會執(zhí)行了。示例為:
<code>try:
text = input('Enter something --> ')
except EOFError:
print('Why did you do an EOF on me?')
except KeyboardInterrupt:
print('You cancelled the operation.')
else:
print('You entered {0}'.format(text))
10.2 拋出異常
可以用raise關(guān)鍵字跑出一個異常對象。異常對象的類型可以是Exception類或任何Exception的子類。定義和跑出異常的示例如下:
<code>class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
text = input('Enter something --> ')
if len(text) < 3:
raise ShortInputException(len(text), 3)
# Other work can continue as usual here
except EOFError:
print('Why did you do an EOF on me?')
except ShortInputException as ex:
print('ShortInputException: The input was {0} long, expected at least {1}'\
.format(ex.length, ex.atleast))
else:
print('No exception was raised.')
10.3 The with statement
使用finally語句來顯示的關(guān)閉文件顯得不夠優(yōu)雅,更棒的方式是用with。示例:
<code>with open("poem.txt") as f:
for line in f:
print(line, end='')
這樣python自動會去關(guān)閉文件,而不需要finally了。關(guān)于with語句的解釋如下:
What happens behind the scenes is that there is a protocol used by the with statement. It fetches the object returned by the open statement, let’s call it “thefile” in this case. It always calls the thefile.__enter__ function before starting the block of code under it and always calls thefile.__exit__ after finishing the block of code.
So the code that we would have written in a finally block should be taken care of automatically by the __exit__method. This is what helps us to avoid having to use explicit try..finally statements repeatedly.
------from
十一, Standard Library(標(biāo)準(zhǔn)庫)
十二, 值得注意的
12.1 Lambda Forms(相當(dāng)于匿名方法)
lambda接受一個表達(dá)式,并將其變成一個函數(shù),表達(dá)式的值就是返回值。看明白了吧,這就是java中的匿名類是一個概念。一個按自定義的排序規(guī)則排序的例子如下:
<code>points = [ { 'x' : 2, 'y' : 3 }, { 'x' : 4, 'y' : 1 } ]
points.sort(key=lambda i : i['y'])
print(points)
12.2 利用tuble賦值
讓一個方法一次返回多個值,或者更方便賦值的方式如下:
<code>Ever wished you could return two different values from a function? You can. All you have to do is use a tuple. >>> def get_error_details(): ... return (2, 'second error details') ... >>> errnum, errstr = get_error_details() >>> errnum 2 >>> errstr 'second error details' Notice that the usage of a, b = <some expression> interprets the result of the expression as a tuple with two values. If you want to interpret the results as (a, <everything else>), then you just need to star it just like you would in function parameters: >>> a, *b = [1, 2, 3, 4] >>> a 1 >>> b [2, 3, 4] This also means the fastest way to swap two variables in Python is: >>> a = 5; b = 8 >>> a, b = b, a >>> a, b (8, 5)
12.3 特殊方法
__init__(self, ...) This method is called just before the newly created object is returned for usage. __del__(self) Called just before the object is destroyed
__str__(self) Called when we use the print function or when str()is used.
__lt__(self, other) Called when the less than operator (<) is used. Similarly, there are special methods for all the operators (+, >, etc.)
__getitem__(self, key) Called when x[key] indexing operation is used.
__len__(self) Called when the built-in len() function is used for the sequence object.
12.4 list的牛逼用法
從已知list來生成一個新的list,新list為原list中大于2的成員乘以2組成。代碼如下:
<code>listone = [2, 3, 4] listtwo = [2*i for i in listone if i > 2] print(listtwo)
12.5 參數(shù)可變方法
方法可以接受tuble和dictionary做為參數(shù),一個*表示tuble,兩個**表示dictionary
There is a special way of receiving parameters to a function as a tuple or a dictionary using the * or ** prefix respectively. This is useful when taking variable number of arguments in the function. >>def powersum(power, *args):
... '''Return the sum of each argument raised to specified power.'''
... total = 0
... for i in args:
... total += pow(i, power)
... return total
...
>>powersum(2, 3, 4)
25
>>powersum(2, 10)
100
Because we have a * prefix on the args variable, all extra arguments passed to the function are stored in args as a tuple. If a ** prefix had been used instead,
the extra parameters would be considered to be key/value pairs of a dictionary