Python 基礎文法(四)

來源:互聯網
上載者:User

標籤:特定   控制   contact   this   python   作業系統   value   __init__   env   

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"

 

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

Python 基礎文法(四)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.