Python基礎文法(四)
25078 ワード
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
十、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ストリームに対応するストリームオブジェクト を含む.
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'、Linuxでは'を使用し、Macでは'r' を使用します. os.sepオペレーティングシステム固有のパス分割子 os.path.split()関数は、パスのディレクトリ名とファイル名 を返します. os.path.isfile()とos.path.isdir()関数は、与えられたパスがファイルであるかディレクトリであるかをそれぞれ検証する os.path.existe()関数は、与えられたパスが本当に存在するかどうかを検証するために使用される 十一、その他
1. いくつかの特殊な方法
名前
説明
__init__(self,...)
このメソッドは、新しいオブジェクトが適切に使用される前に呼び出されます.
__del__(self)
オブジェクトが削除される前に呼び出されます.
__str__(self)
オブジェクトに対して
__lt__(self,other)
より小さい演算子(<)を使用すると呼び出されます.同様に、すべての演算子(+,>など)に対して特別な方法があります.
__getitem__(self,key)
__len__(self)
シーケンスオブジェクトに組み込まれた
次のクラスでは、上記の表のメソッドを定義します.
2. 総合リスト
リスト統合により、既存のリストから新しいリストをエクスポートできます.
3. 関数受信タプル/リスト/ディクショナリ
関数がメタグループまたは辞書形式のパラメータを受信する場合、*および**接頭辞を使用する特殊な方法があります.この方法は,関数が可変数のパラメータを取得する必要がある場合に特に有用である.
args変数の前に*接頭辞があるため、余分な関数パラメータはすべてargsにメタグループとして格納されます.**接頭辞を使用している場合、余分なパラメータは辞書とみなされます.
を選択します.
4. lambda
Lambda文は、新しい関数オブジェクトを作成し、実行時に返すために使用されます.Lambdaにはパラメータが必要で、後に単一の式だけを関数体として、式の値はこれによって
新しい関数が返されます.print文でもlambda形式では使用できず、式しか使用できません.
5. exec/eval
exec文は、文字列またはファイルに格納されたPython文を実行するために使用されます.eval文は、文字列に格納された有効なPython式を計算するために使用されます.
6. assert
assert文は、ある条件が本当であることを断言し、それが本当ではないときにエラーを引き起こすために使用されます.
7. repr関数
repr関数は、オブジェクトの仕様文字列表現を取得するために使用されます.逆引用符(変換子とも呼ばれる)は、同じ機能を実行できます.
ほとんどの場合、eval(repr(object)==objectがあります.
クラスの__を定義できます.repr__メソッドは、repr関数によって呼び出されたときにオブジェクトが返す内容を制御します.
十二、練習
通信録を実現し、主な機能:すべての連絡先を追加、削除、更新、照会、表示する.
------------------------------------------------------------------------------------------------------------
十、Python標準ライブラリ
Python標準ライブラリはPthonに付属してインストールされており、非常に有用なモジュールが多数含まれています.
1. Sysモジュールsysモジュールはシステム対応の機能を含む
s = sys.stdin.readline()
sys.stdout.write(s)
2. osモジュール一般的なオペレーティングシステム機能を含む
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"
------------------------------------------------------------------------------------------------------------