Python 基礎語法(四)


 --------------------------------------------接 Python 基礎語法(三) --------------------------------------------

十、Python標准庫

  Python標准庫是隨Pthon附帶安裝的,包含了大量極其有用的模塊。

  1. sys模塊  sys模塊包含系統對應的功能

  • sys.argv  ---包含命令行參數,第一個參數是py的文件名
  • sys.platform  ---返回平台類型
  • sys.exit([status])  ---退出程序,可選的status(范圍:0-127):0表示正常退出,其他表示不正常,可拋異常事件供捕獲
  • sys.path    ---程序中導入模塊對應的文件必須放在sys.path包含的目錄中,使用sys.path.append添加自己的模塊路徑
  • sys.modules  ---This is a dictionary that maps module names to modules which have already been loaded
  • sys.stdin,sys.stdout,sys.stderr  ---包含與標准I/O 流對應的流對象
s = sys.stdin.readline()

sys.stdout.write(s)

  2. os模塊  該模塊包含普遍的操作系統功能

  • os.name字符串指示你正在使用的平台。比如對於Windows,它是'nt',而對於Linux/Unix用戶,它是'posix'
  • os.getcwd()函數得到當前工作目錄,即當前Python腳本工作的目錄路徑
  • os.getenv()和os.putenv()函數分別用來讀取和設置環境變量
  • os.listdir()返回指定目錄下的所有文件和目錄名
  • os.remove()函數用來刪除一個文件
  • os.system()函數用來運行shell命令
  • os.linesep字符串給出當前平台使用的行終止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'
  • os.sep 操作系統特定的路徑分割符
  • os.path.split()函數返回一個路徑的目錄名和文件名
  • os.path.isfile()和os.path.isdir()函數分別檢驗給出的路徑是一個文件還是目錄
  • os.path.existe()函數用來檢驗給出的路徑是否真地存在

十一、其他

  1. 一些特殊的方法

名稱 說明
__init__(self,...) 這個方法在新建對象恰好要被返回使用之前被調用。
__del__(self) 恰好在對象要被刪除之前調用。
__str__(self) 在我們對對象使用print語句或是使用str()的時候調用。
__lt__(self,other) 當使用 小於 運算符(<)的時候調用。類似地,對於所有的運算符(+,>等等)都有特殊的方法。
__getitem__(self,key) 使用x[key]索引操作符的時候調用。
__len__(self) 對序列對象使用內建的len()函數的時候調用。

  下面的類中定義了上表中的方法:

class Array:
__list = []

def __init__(self):
print "constructor"

def __del__(self):
print "destructor"

def __str__(self):
return "this self-defined array class"

def __getitem__(self, key):
return self.__list[key]

def __len__(self):
return len(self.__list)

def Add(self, value):
self.__list.append(value)

def Remove(self, index):
del self.__list[index]

def DisplayItems(self):
print "show all items----"
for item in self.__list:
print item

arr = Array() #constructor
print arr #this self-defined array class
print len(arr) #0
arr.Add(1)
arr.Add(2)
arr.Add(3)
print len(arr) #3
print arr[0] #1
arr.DisplayItems()
#show all items----
#
1
#
2
#
3
arr.Remove(1)
arr.DisplayItems()
#show all items----
#
1
#
3
#
destructor

  2. 綜合列表

    通過列表綜合,可以從一個已有的列表導出一個新的列表。

list1 = [1, 2, 3, 4, 5]
list2 = [i*2 for i in list1 if i > 3]

print list1 #[1, 2, 3, 4, 5]
print list2 #[8, 10]

  3. 函數接收元組/列表/字典

    當函數接收元組或字典形式的參數的時候,有一種特殊的方法,使用*和**前綴。該方法在函數需要獲取可變數量的參數的時候特別有用。

    由於在args變量前有*前綴,所有多余的函數參數都會作為一個元組存儲在args中。如果使用的是**前綴,多余的參數則會被認為是一個字典

  的鍵/值對。

def powersum(power, *args):
total = 0
for i in args:
total += pow(i, power)
return total

print powersum(2, 1, 2, 3) #14

 

def displaydic(**args):
for key,value in args.items():
print "key:%s;value:%s" % (key, value)


displaydic(a="one", b="two", c="three")
#key:a;value:one
#
key:c;value:three
#
key:b;value:two

  4. lambda

    lambda語句被用來創建新的函數對象,並在運行時返回它們。lambda需要一個參數,后面僅跟單個表達式作為函數體,而表達式的值被這個

  新建的函數返回。 注意,即便是print語句也不能用在lambda形式中,只能使用表達式。

func = lambda s: s * 3
print func("peter ") #peter peter peter

func2 = lambda a, b: a * b
print func2(2, 3) #6

  5. exec/eval

    exec語句用來執行儲存在字符串或文件中的Python語句;eval語句用來計算存儲在字符串中的有效Python表達式。

cmd = "print 'hello world'"
exec cmd #hello world

expression = "10 * 2 + 5"
print eval(expression) #25

  6. assert

    assert語句用來斷言某個條件是真的,並且在它非真的時候引發一個錯誤--AssertionError

flag = True

assert flag == True

try:
assert flag == False
except AssertionError, err:
print "failed"
else:
print "pass"

  7. repr函數

    repr函數用來取得對象的規范字符串表示。反引號(也稱轉換符)可以完成相同的功能。

    注意,在大多數時候有eval(repr(object)) == object。

    可以通過定義類的__repr__方法來控制對象在被repr函數調用的時候返回的內容。

arr = [1, 2, 3]
print `arr` #[1, 2, 3]
print repr(arr) #[1, 2, 3]

十二、練習

    實現一個通訊錄,主要功能:添加、刪除、更新、查詢、顯示全部聯系人。

 1 import cPickle
2 import os
3 import sys
4
5 class Contact:
6 def __init__(self, name, phone, mail):
7 self.name = name
8 self.phone = phone
9 self.mail = mail
10
11 def Update(self, name, phone, mail):
12 self.name = name
13 self.phone = phone
14 self.mail = mail
15
16 def display(self):
17 print "name:%s, phone:%s, mail:%s" % (self.name, self.phone, self.mail)
18
19
20 # begin
21
22 # file to store contact data
23 data = os.getcwd() + os.sep + "contacts.data"
24
25 while True:
26 print "-----------------------------------------------------------------------"
27 operation = raw_input("input your operation(add/delete/modify/search/all/exit):")
28
29 if operation == "exit":
30 sys.exit()
31
32 if os.path.exists(data):
33 if os.path.getsize(data) == 0:
34 contacts = {}
35 else:
36 f = file(data)
37 contacts = cPickle.load(f)
38 f.close()
39 else:
40 contacts = {}
41
42 if operation == "add":
43 flag = False
44 while True:
45 name = raw_input("input name(exit to back choose operation):")
46 if name == "exit":
47 flag = True
48 break
49 if name in contacts:
50 print "the name already exists, please input another or input 'exit' to back choose operation"
51 continue
52 else:
53 phone = raw_input("input phone:")
54 mail = raw_input("input mail:")
55 c = Contact(name, phone, mail)
56 contacts[name] = c
57 f = file(data, "w")
58 cPickle.dump(contacts, f)
59 f.close()
60 print "add successfully."
61 break
62 elif operation == "delete":
63 name = raw_input("input the name that you want to delete:")
64 if name in contacts:
65 del contacts[name]
66 f = file(data, "w")
67 cPickle.dump(contacts, f)
68 f.close()
69 print "delete successfully."
70 else:
71 print "there is no person named %s" % name
72 elif operation == "modify":
73 while True:
74 name = raw_input("input the name which to update or exit to back choose operation:")
75 if name == "exit":
76 break
77 if not name in contacts:
78 print "there is no person named %s" % name
79 continue
80 else:
81 phone = raw_input("input phone:")
82 mail = raw_input("input mail:")
83 contacts[name].Update(name, phone, mail)
84 f = file(data, "w")
85 cPickle.dump(contacts, f)
86 f.close()
87 print "modify successfully."
88 break
89 elif operation == "search":
90 name = raw_input("input the name which you want to search:")
91 if name in contacts:
92 contacts[name].display()
93 else:
94 print "there is no person named %s" % name
95 elif operation == "all":
96 for name, contact in contacts.items():
97 contact.display()
98 else:
99 print "unknown operation"

 

-----------------------------------------------------   結束  -----------------------------------------------------

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM