Python 簡明教程學習筆記
數據結構()
list用法:
shoplist = ['apple', 'mango', 'carrot', 'banana']
len(shoplist)
for item in shoplist:
shoplist.append('rice')
shoplist.sort()
shoplist[0]
元組
zoo = ('wolf', 'elephant', 'penguin')
len(zoo)
new_zoo = ('monkey', 'dolphin', zoo)
new_zoo[2][2]表示企鵝
new_zoo[2]表示zoo這個元組
字典
ab = { 'Swaroop' : 'swaroopch@byteofpython.info',
'Larry' : 'larry@wall.org',
'Matsumoto' : 'matz@ruby-lang.org',
'Spammer' : 'spammer@hotmail.com'
}
ab['Guido']
del ab['Spammer']
for name, address in ab.items():
if 'Guido' in ab:
序列
索引
shoplist[0] 【0】作為該LIST得索引
切片
shoplist[0:1] 【0:1】作為切片表示從0開始1結束
參考
mylist=shoplist mylist作為shoplist的副本,mylist的item改變不會影響shoplist,而shoplist改變則會影響mylist
字符串
name='Swaroop'
if name.startswith('Swa'):
if 'a' in name:
if name.find('war')!=-1:
面向對象()
類使用class關鍵字創建。類的域(變量)和方法被列在一個縮進塊中。
類的方法和普通函數只有一個區別,類的方法必須有一個額外的第一個參數的名稱,但是在調用這個方法的時候你不為這個參數賦值,由PYTHON提供這個值,這個特別的變量指對象本身,按照慣例他的名稱是self
有一個類MyClass和這個類的對象MyObject :MyObject.method(arg1,arg2)的時候python自動轉化為MyClaa.method(MyObject,arg1,arg2)
創建一個類:
class Person:
pass # An empty block
p=Person()
print p
輸出:<__main__.Person instance at 0xf6fcb18c>
可以注意到存儲對象的計算機內存地址打印出來了,因為Python可以在任何空位存儲對象
使用對象的方法:
class Person:
def sayHi(self):
print 'hello,how are you?'
p=person()
p.syaHi()
注意:sayHi方法沒有任何參數,但仍然在函數定義時有self。
__init__方法和__del__方法
class Person:
def __init__(self,name):
self.name=name
def sayHi(self):
print 'hello,my name is',self.name
p=Person('Swaroop')
p.sayHi()
輸出:hello,my name is Swaroop
__init__()方法,只是在創建類的新實例的時候,把參數包括在括號內跟在類名后面,從而傳遞給_init()方法。ps相當于:java中的構造函數
__del__()方法,在對象消逝的時候調用
類和對象的方法:
類的變量和對象的變量不同:對象的變量賦值如"self.name" 而類的變量"name"
所有的類成員都是公共的 但以雙下劃線為前綴的數據成員如:__a,Python會有效的把他作為似有變量.
慣例:如果某個變量只想在類和對象中使用,就應該以單下劃線為前綴。
繼承:
class SchoolMember:
def __init__(self,name,age):
self.name=name
self.age=age
print '(Initialized SchoolMember:%s)'%self.name
del tell(self):
print 'Name:"%s" Age:"%s"'%(self.name,self.age)
class Teacher(SchoolMember):
def __init__(slef,name,age,salary)
SchoolMember.__init__(self,name,age)
self.salary=salary
del tell(self):
SchoolMember.tell(self)
print'salary:"%d"'%slef.salary
__init__方法專門使用self變量調用,這樣我們就可以初始化對象的基本類部分。
這一點十分重要——Python不會自動調用基本類的constructor,必須手動自己調用。
如果在繼承元組中列了一個以上的類,那么它就被稱作 多重繼承
輸入輸出()
raw_input和print 輸入和輸出:
文件:
file類的對象來打開一個文件,分別使用file類的方法read,readline,write方法來恰當的讀寫文件,完成對文件的操作時,調用close方法
poem='''write into file's content'''
f=file('poem.txt','w')
f.write(poem)
f.close()
f=file('poem.txt')
while True:
line=f.readline()
if len(line)==0:
break
print line
f.close()
注意:只讀模式'r',寫入模式'w',追加模式'a',不指定為只讀模式.
存儲器(pickle):
pickle和cPickle的區別,功能相同,cPickle(C語言寫的)比pickle更快
import cPickle as p
shoplistfile='shoplist.data'
shoplist = ['apple', 'mango', 'carrot']
f = file(shoplistfile, 'w')
p.dump(shoplist,f)#dump the object to a file
f.close()
del shoplist
f=file(shoplistfile)
storedlist=p.load(f)
print storedlist
異常()
try..except:
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program
print 'Done'
將有可能發生錯誤的語句放入try:語句中,用except:來處理這些錯誤,對于每一個try從句至少有一個except從句與其關聯
引發異常:
raise語句
class ShorInputException(Exception):
def __init__(self,length,atleast):
Exception.__init__(self)
self.length=length
self.atleast=atleast
try:
s=raw_input('Enter something-->')
if len(s)<3:
raise ShorInputException(len(s),3)
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShorInputException,x:
print 'ShortInputException: The input was of length %d, \
was expecting at least %d' % (x.length, x.atleast)
else:
print 'No exception was raised'
try...finally:
Python標準庫()
sys模塊:
os模塊:
os.name返回操作系統平臺
os.getcwd()返回當前工作目錄
os.getenv(),os.putenv讀取和設置環境變量
os.listdir返回指定目錄下的所有文件和目錄名
os.remove() 刪除一個文件
os.system()用來運行shell命令
os.linesep字符串給出當前平臺的行終止符,windows-'\r\n'linx-'\n'mac-'\r'
os.path.split()返回一個路徑的目錄名和文件名
os.path.isfile(),os.path.isdir()分別檢測是文件還路徑
os.path.existe用來檢測給出的路徑是否存在
更多()
特殊的方法:
__init__()
__del__()
__getitem__()可以用來獲取元組或list相對位置的值
在函數中接收元組和列表:
當要使函數接收元組或字典形式的參數的時候,有一種特殊的方法,它分別使用*和**前綴。這種方法在函數需要獲取可變數量的參數的時候特別有用。
def powersum(power, *args):
total=0
for i in args:
total+=pow(i,power)
return total
>>> powersum(2,3,4)
25
>>> powersum(2,10)
100
由于args變量前有*前綴,所有多余的函數參數都會作為一個元組存在args中,如果**為前綴,那么對于的參數會被認為是字典的鍵/值對
lambda形式:
def make_repeater(n):
return lambda s:
s*n
twice=mak_repeater(2)
print twice('word')
print twice(5)
輸出:wordword
10
注意:lambda語句用來創建函數對象,lambda需要一個參數(s)這個參數作為函數體,而表達式的質被這個新建的函數返回。注意即便是print語句也不能用在lambda形式中,只能使用表達式.
猜想:
exec和eval語句:
>>>exec 'print "hello world"'
hello world
>>>eval('2*3')
6
exec用來執行存儲在文件或字符串中的python語句
eval用來執行存儲在字符串中的python表達式 本文由用戶 ecy2 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!