Python簡明教程,此資源位于http://woodpecker.org.cn/abyteofpython_cn/chinese/ s=u'中文字符' #u表示unicode,使用u之后能正常顯示中文 s='''多行文本 這是第二哈''' #'''表示多行注釋。也可以用""" 布爾型:True,False docString:文檔字符串。eg:
# Filename : nice.py # encoding:utf8 def printMax(x, y): u'''輸出兩個數字中大的一個。 兩個數字的值必須是整數''' x=int(x) y=int(y) if x>y: print x,'is maximum' else: print y,'is maximum' printMax(3,5) print printMax.__doc__
會把中文注釋都輸出 python使用模塊: ·sys模塊:
# Filename : nice.py # encoding:utf8 import sys for i in sys.argv: print i
或者,使用:
# Filename : nice.py # encoding:utf8 from sys import argv for i in argv: print i
在vim中執行w之后, 執行!python % 123 sdfds 那么將輸出123 sdfds(分兩行輸出) ·使用__main__模塊:
# Filename : nice.py # encoding:utf8 if __name__=='__main__': print 'This program is being run by itself' else: print 'I am being imported from another module'
·使用自定義的模塊
# Filename : nice.py # encoding:utf8 import mymodule mymodule.sayhi() print 'Version', mymodule.version
# Filename:mymodule.py # encoding:utf8 def sayhi(): print 'Hi, this is my module.' version = '0.1'
數據結構部分: 使用列表list:
# Filename : nice.py # encoding:utf8 shoplist=['apple','mango', 'carrot', 'banana'] print 'I have', len(shoplist),'items to purchase.' print 'These items are:', for item in shoplist: print item, print '\nI alse have to buy rice.' shoplist.append('rice') print 'My shopping list is now', shoplist print 'I will sort my list now' shoplist.sort() print 'Sorted shopping list is', shoplist print 'The first item I will buy is', shoplist[0] olditem=shoplist[0] del shoplist[0] print 'I bought the', olditem print 'My shopping list is now', shoplist
·元組的使用:類似于數組,但是可以嵌套用
# Filename : nice.py # encoding:utf8 zoo=('wolf','elephant','penguin') print 'Number of animals in the zoo is', len(zoo) new_zoo=('monkey','dolphin',zoo) print 'Number of animals in the new zoo is', len(new_zoo) print 'All animals in new zoo are', new_zoo print 'Animals brought from old zoo are', new_zoo[2] print 'Last animal brought from old zoo is', new_zoo[2][2]
·使用元組輸出(print語句中的參數輸出哈哈)
# Filename : nice.py # encoding:utf8 age=22 name='Swaroop' print '%s is %d years old' % (name, age) print 'Why is %s playing with that python' % name
·使用字典(好吧,我表示寫過幾個不太成功的http post請求的腳本之后,知道什么是字典了。。。)
# Filename : nice.py # encoding:utf8 ab={'Swaroop':'swaroopch@byteofpyton.info', 'Larry':'larry@wall.org', 'Matsumoto':'matz@ruby-lang.org', 'Spammer':'spammer@hotmail.com' } print "Swaroop's address is %s" % ab['Swaroop'] ab['Guido']='guido@python.org' del ab['Spammer'] print '\nThere are %d contacts in the address-book\n' % len(ab) for name, address in ab.items(): print 'Contact %s at %s' % (name, address) if 'Guido' in ab: print "\nGuido's address is %s" % ab['Guido']
·所謂的“索引與切片”,我認為只是玩弄下標的小把戲(包括數組,列表和字符串) ·對象與參考
# Filename : nice.py # encoding:utf8 print 'Simple Assignment' shoplist=['apple','mango', 'carrot', 'banana'] mylist=shoplist del shoplist[0] print 'shoplist is', shoplist print 'mylist is', mylist print 'Copy by making a full slice' mylist=shoplist[:] del mylist[0] print 'shoplist is', shoplist print 'mylist is', mylist
直接用=賦值,那么兩個對象指向同一個存在。(兩者是同一事物) 如果使用[:](這應該叫做切片了吧),那么兩者為不通的對象 ·幾個擴展的字符串方法:
# Filename : nice.py # encoding:utf8 name ='Swaroop' if name.startswith('Swa'): print 'Yes, the string starts with "Swa"' if 'a' in name: print 'Yes, it contains the string "a"' if name.find('war') != -1: print 'Yes, it contains the string "war"' delimiter='_*_' mylist=['Brazil','Russia','India','China'] print delimiter.join(mylist)
【面向對象】 談python的面向對象了。python就是這么強大。 self關鍵字: 類的方法區別于普通函數之處:第一個參數一定是self(也可以換為別的關鍵字但是不建議)。 這個self作用是,當類的一個實例對象調用類的方法的時候,self指的是這個對象本身。 {我認為在類的方法的參數列表中寫self沒有必要,使用約定俗成的this其實更好} ·類的創建:
# Filename : nice.py # encoding:utf8 class Person: def sayHi(self): print 'Hello, how are you?' p=Person() p.sayHi()
·__init__方法:其實就是constructor
# Filename : nice.py # encoding:utf8 class Person: def __init__(self,name): self.name=name def sayHi(self): print 'Hello, my name is', self.name p=Person("Chris") p.sayHi()
·__del__方法:類似于destructor (不過下面這個例子的運行結果讓人很暈,明明沒有調用__del__,但結果表明它偷偷的執行了)
# Filename : nice.py # encoding:utf8 class Person: '''Represents a person.''' population = 0 def __init__(self,name): '''Initializes the preson's data.''' self.name = name print '(Initializing %s)'%self.name #When this person is created, he/she #adds to the population Person.population += 1 def __del__(self): '''I am dying.''' print '%s says bye.'%self.name Person.population -= 1 if Person.population == 0: print 'I am the last one.' else: print 'There are still %d people left.'%Person.population def sayHi(self): '''Greeting by the person. Really, that's all it does.''' print 'Hi, my name is %s.'%self.name def howMany(self): '''Prints the current population.''' if Person.population == 1: print 'I am the only person here.' else: print 'We have %d persons here.'%Person.population swaroop=Person('Swaroop') swaroop.sayHi() swaroop.howMany() kalam=Person('Abdul Kalam') kalam.sayHi() kalam.howMany() swaroop.sayHi() swaroop.howMany()
·類繼承的一個例子:
# Filename : nice.py # encoding:utf8 class SchoolMember: '''Represents any school member.''' def __init__(self, name, age): self.name=name self.age=age print '(Initialized SchoolMember: %s)'%self.name def tell(self): '''Tell my details.''' print 'Name:"%s" Age:"%s"'%(self.name,self.age), class Teacher(SchoolMember): '''Represents a teacher.''' def __init__(self,name,age, salary): SchoolMember.__init__(self,name,age) self.salary=salary print '(Initialized Teacher: %s)'%self.name def tell(self): SchoolMember.tell(self) print 'Salary: "%d"'%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: %s)'%self.name def tell(self): SchoolMember.tell(self) print 'Marks: "%d"'%self.marks t=Teacher('Mrs. Shrividya', 40, 30000) s=Student('Swaroop', 22, 75) print #輸出一個空白行 members=[t,s] for member in members: member.tell()
【Python中的逗號】 在循環輸出一行字符串的時候使用逗號結尾,可以避免多輸出空的換行 ·python的文件操作: f=file('file_name',mode) f.write(str) f.close() f.readline() 一個例子:
# Filename : nice.py # encoding:utf8 poem='''\ Programming is fun When the work is done if you wanna make your work also fun use Python! ''' f=file('poem.txt','w') #打開文件,寫入形式 f.write(poem) f.close() f=file('poem.txt') #如果沒有指定模式,默認使用read模式 while True: line=f.readline() if len(line)==0:#長度為0的行,意味著文件結束(EOF) break print line, f.close()
·異常處理 一個EOFError的例子:
# Filename : nice.py # encoding:utf8 import sys try: s=raw_input('Enter something --> ') except EOFError: print '\nWhy did you do an EOF on me?' sys.exit() except: print '\nSome error/exception occurred.' print 'Done'
·列表綜合 一個簡潔的列表:
# Filename : nice.py # encoding:utf8 listone=[2,3,4] listtwo=[2*i for i in listone if i>2] print listtwo
函數接受不定個數參數的時候,使用* eg:
# Filename : nice.py # encoding:utf8 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 print powersum(2,3,4) print powersum(2,10)
使用lambda
# Filename : nice.py # encoding:utf8 def make_repeater(n): return lambda s:s*n twice=make_repeater(2) print twice('word') print twice(5)
exec:用來執行存儲在字符串中的python表達式 eg:
# Filename : nice.py # encoding:utf8 eval('print "Hello world"')
repr函數:用來取得對象的規范字符串表示。效果和反引號相同 eg
i=[] i.append('item') print `i` print repr(i)
有一道題目這樣描述: “創建一個類來表示一個人的信息。使用字典儲存每個人的對象,把他們的名字作為鍵。 使用cPickle模塊永久地把這些對象儲存在你的硬盤上。使用字典內建的方法添加、 刪除和修改人員信息。 一旦你完成了這個程序,你就可以說是一個Python程序員了。” 在網上找過了,基本上功能好實現(例如http://iris.is-programmer.com/2011/5/16/addressbook.26781.html) 但我想知道保存到硬盤的data文件中的內容(用pickle存儲的),在user選擇modify的時候,是否能夠修改?and what about delete? I' m confuse about it, and many code version doesn't deal with the data file well. Once I re-run the python file, the stored data is empty, because 他們不從data文件中read數據! About GUI in Python: There are several tools we can use. They are: PyQt: works well in Linux. Not free in windows PyGTK: works well in Linux. wxPython:windows下可以用。免費。 TkInter:據說IDLE就是這個開發的 TkInter是標準Python發行版的一部分。在Linux和Windows下都可以用
文章列表