Python:Python学习总结
背景
PHP的$和->讓人輸入的手疼(PHP確實(shí)非常簡(jiǎn)潔和強(qiáng)大,適合WEB編程),Ruby的#、@、@@也好不到哪里(OO人員最該學(xué)習(xí)的一門(mén)語(yǔ)言)。
Python應(yīng)該是寫(xiě)起來(lái)最舒服的動(dòng)態(tài)語(yǔ)言了,一下是一些讀書(shū)筆記,最后會(huì)介紹一下高級(jí)的用法:Mixin、Open Class、Meta Programming和AOP。
文中有些地方是用2.7開(kāi)發(fā)的,如果您安裝的是3.x,有幾點(diǎn)需要注意:
- print "xxx" 要換成 print("xxx")
- __metaclass__ = type 刪除掉。
類(lèi)型和表達(dá)式部分
你好,世界!
1 # coding=utf-8 2 3 print "你好,世界。"?乘方
1 print 2**10變量
1 var = 1 2 print var 3 4 var = "段光偉" 5 print var注:這里的var = xxxx不叫變量賦值,而叫變量綁定,python維護(hù)了一個(gè)符號(hào)表(變量名)以及符合對(duì)應(yīng)的值,這個(gè)對(duì)應(yīng)關(guān)系就叫做綁定,一個(gè)符號(hào)可以綁定任意類(lèi)型的值。
獲取用戶(hù)輸入
1 #獲取用戶(hù)輸入 2 x = input("x:") 3 y = input("y:") 4 5 print x*y注:input接受的是Python代碼,輸入中可以訪問(wèn)當(dāng)前執(zhí)行環(huán)境中的變量,如果想獲取原始輸入需要使用?raw_input。
函數(shù)定義
1 def say_b(): 2 print "b"強(qiáng)類(lèi)型
Javascript和Php是弱類(lèi)型的,Python和Ruby是強(qiáng)類(lèi)型的。弱類(lèi)型允許不安全的類(lèi)型轉(zhuǎn)換,強(qiáng)類(lèi)型則不允許。
1 #1 + “1” 這行代碼在Python中會(huì)報(bào)錯(cuò)。 2 print 1 + int("1") 3 print str(1) + "1"?字符串
1 #字符串 2 print '''' 段 3 光 4 偉''' 5 print r'C:\log.txt' 6 print 'C:\\log.txt'序列
這里先介紹三種序列:列表、元祖和字符串。
序列通用操作
1 seq = "0123456789"2 print seq[0] #從0開(kāi)始編碼。3 print seq[-1] #支持倒著數(shù)數(shù),-1代表倒數(shù)第一。4 print seq[1:5] #支持分片操作,seq[start:end],start會(huì)包含在結(jié)果中,end不會(huì)包含在結(jié)果中。5 print seq[7:] #seq[start:end]中的end可以省略。6 print seq[-3:] #分片也支持負(fù)數(shù)。7 print seq[:3] #seq[start:end]中的start也可以省略。8 print seq[:] #全部省略會(huì)復(fù)制整個(gè)序列。9 print seq[::2] #支持步長(zhǎng)。 10 print seq[::-2] #支持負(fù)步長(zhǎng)。 11 print seq[9:1:-1] #支持負(fù)步長(zhǎng)。 12 print [1, 2, 3] + [4, 5, 6] # 序列支持相加,這解釋了為啥字符串可以相加。 13 print [1, 2, 3] * 3 #序列支持相乘,這解釋了為啥字符串可以相稱(chēng)。 14 print [None] * 10 #生成一個(gè)空序列。 15 print 1 in [1, 2, 3] #成員判斷。?可變的列表
1 data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];2 3 data[0] = "a" #修改元素。4 print data5 data[0] = 06 7 del data[10] #刪除元素。8 print data9 10 del data[8:] #分片刪除。 11 print data 12 13 data[8:] = [8, 9, 10] #分片賦值 14 print data不可變的元祖
1 print (1, 2) #元祖以小括號(hào)形式聲明。 2 print (1,) #一個(gè)元素的元祖。字符串格式化
1 print "% 10s" % "----" 2 3 print ''' 4 %(title)s 5 %(body)s 6 ''' % {"title": "標(biāo)題", "body": "內(nèi)容"}字典
1 print {"title": "title", "body": "body"} 2 print dict(title = "title", body = "body") 3 print dict([("title", "title"), ("body", "body")]) 1 dic = {"title": "title", "body": "body"}; 2 print dic["title"] 3 del dic["title"] 4 print dicprint 語(yǔ)句
1 print 'a', 'b' #print可以接受多個(gè)參數(shù),參數(shù)的輸出之間以空格相隔。 2 print 'a', #如果逗號(hào)之后沒(méi)有參數(shù),則不會(huì)換行。 3 print 'b'序列解包
1 x, y, z = 1, 2, 3 2 print x, y, z 3 (x, y, z) = (1, 2, 3) 4 print x, y, z 5 (x, y, z) = [1, 2, 3] 6 print x, y, zbool值
1 #下面的輸入全部返回False。2 print(bool(None))3 print(bool(()))4 print(bool([]))5 print(bool({}))6 print(bool(""))7 print(bool(0))8 9 #雖然這些值在條件運(yùn)算中會(huì)當(dāng)做False,但是本身不等于False。 10 print(True and "") 11 print(not "") 12 print(False == "") 13 print(False == 0) #0除外,bool類(lèi)型的內(nèi)部表示就是int類(lèi)型。bool運(yùn)算
1 print(0 < 1 < 10) 2 print(0 < 1 and 1 < 10) 3 print(not(0 > 1 > 10)) 4 print(not(0 > 1 or 1 > 10))語(yǔ)句塊
:開(kāi)始語(yǔ)句快,縮進(jìn)的所有內(nèi)容都是一個(gè)語(yǔ)句塊。
1 if(10 > 1): 2 print("10 > 1") 3 else: 4 print("不可能發(fā)生")三元運(yùn)算符
1 print("10 > 1" if 10 > 1 else "不可能發(fā)生")相等比較
1 #== 和 is的差別,==比較的是內(nèi)容,is比較的是引用。 2 x = [1, 2, 3] 3 y = x 4 z = [1, 2, 3] 5 print(x == y) 6 print(x == z) 7 print(x is y) 8 print(x is z)循環(huán)
1 #for循環(huán)類(lèi)似C#的foreach,注意for后面是沒(méi)有括號(hào)的,python真是能簡(jiǎn)潔就盡量簡(jiǎn)潔。2 for x in range(1, 10):3 print(x)4 5 for key in {"x":"xxx"}:6 print(key)7 8 for key, value in {"x":"xxx"}.items():9 print(key, value) 10 11 for x, y, z in [["a", 1, "A"],["b", 2, "B"]]: 12 print(x, y, z) 1 #帶索引的遍歷2 for index, value in enumerate(range(0, 10)):3 print(index, value)4 5 #好用的zip方法6 for x, y in zip(range(1, 10), range(1, 10)):7 print(x, y)8 9 #循環(huán)中的的else子句 10 from math import sqrt 11 for item in range(99, 1, -1): 12 root = sqrt(item) 13 if(root == int(root)): 14 print(item) 15 break 16 else: 17 print("沒(méi)有執(zhí)行break語(yǔ)句。")pass、exec和eval
1 #pass、exec、eval 2 if(1 == 1): 3 pass 4 5 exec('print(x)', {"x": "abc"}) 6 print(eval('x*2', {"x": 5}))函數(shù)部分
形參和實(shí)參之間是按值傳遞的,當(dāng)然有些類(lèi)型的值是引用(對(duì)象、列表和字典等)。
1 # 基本函數(shù)定義。2 def func():3 print("func")4 5 func()6 7 # 帶返回值的函數(shù)。8 def func_with_return():9 return ("func_with_return") 10 11 print(func_with_return()) 12 13 # 帶多個(gè)返回值的函數(shù)。 14 def func_with_muti_return(): 15 return ("func_with_muti_return", "func_with_muti_return") 16 17 print(func_with_muti_return()) 18 19 # 位置參數(shù) 20 def func_with_parameters(x, y): 21 print(x, y) 22 23 func_with_parameters(1, 2) 24 25 # 收集多余的位置參數(shù) 26 def func_with_collection_rest_parameters(x, y, *rest): 27 print(x, y) 28 print(rest) 29 30 func_with_collection_rest_parameters(1, 2, 3, 4, 5) 31 32 #命名參數(shù) 33 def func_with_named_parameters(x, y, z): 34 print(x, y, z) 35 36 func_with_named_parameters(z = 1, y = 2, x = 3) 37 38 #默認(rèn)值參數(shù) 39 def func_with_default_value_parameters(x, y, z = 3): 40 print(x, y, z) 41 42 func_with_default_value_parameters(y = 2, x = 1) 43 44 #收集命名參數(shù) 45 def func_with_collection_rest_naned_parameters(*args, **named_agrs): 46 print(args) 47 print(named_agrs) 48 49 func_with_collection_rest_naned_parameters(1, 2, 3, x = 4, y = 5, z = 6) 50 51 #集合扁平化 52 func_with_collection_rest_naned_parameters([1, 2, 3], {"x": 4, "y": 4, "z": 6}) #這會(huì)導(dǎo)致args[0]指向第一個(gè)實(shí)參,args[1]指向第二個(gè)實(shí)參。 53 func_with_collection_rest_naned_parameters(*[1, 2, 3], **{"x": 4, "y": 4, "z": 6}) #這里的執(zhí)行相當(dāng)于func_with_collection_rest_naned_parameters(1, 2, 3, x = 4, y = 5, z = 6)。作用域
1 # coding=utf-82 3 # 只有函數(shù)執(zhí)行才會(huì)開(kāi)啟一個(gè)作用域。4 if(2 > 1):5 x = 16 7 print(x) # 會(huì)輸出1。8 9 10 # 使用vars()函數(shù)可以訪問(wèn)當(dāng)前作用域包含的變量。 11 x = 1 12 print(vars()["x"]) 13 14 # 使用globals()函數(shù)可以訪問(wèn)全局作用域。 15 x = 1 16 17 def func(): 18 print(globals()["x"]) 19 20 func() 21 22 # 使用locals()函數(shù)可以訪問(wèn)局部作用域。 23 def func(): 24 x = 2 25 print(locals()["x"]) 26 27 func() 28 29 # 每個(gè)函數(shù)定義時(shí)都會(huì)記住所在的作用域。 30 # 函數(shù)執(zhí)行的時(shí)候會(huì)開(kāi)啟一個(gè)新的作用域,函數(shù)內(nèi)變量訪問(wèn)的規(guī)則是:先訪問(wèn)當(dāng)前作用域,如果沒(méi)有就訪問(wèn)函數(shù)定義時(shí)的作用域,遞歸直到全局作用域。 31 x = 1 32 33 def func(): 34 y = 2 35 print(x, y) # 輸出1 2 36 37 func() 38 39 40 # 變量賦值始終訪問(wèn)的是當(dāng)前作用域。 41 x = 1 42 43 def func(): 44 x = 2 45 y = 2 46 print(x, y) # 輸出2 2 47 48 func() 49 print(x) #輸出 1 50 51 # 局部變量會(huì)覆蓋隱藏全局變量,想訪問(wèn)全局變量可以采用global關(guān)鍵字或globals()函數(shù)。 52 x = 1 53 54 def func(): 55 global x 56 x = 2 57 y = 2 58 print(x, y) # 輸出2 2 59 60 func() 61 print(x) #輸出 2 1 # python支持閉包2 def func(x):3 def inner_func(y):4 print(x + y)5 6 return inner_func7 8 inner_func = func(10)9 inner_func(1) 10 inner_func(2) 1 #函數(shù)作為對(duì)象 2 def func(fn, arg): 3 fn(arg) 4 5 func(print, "hello") 6 func(lambda arg : print(arg), "hello")模塊
幾個(gè)模塊相關(guān)的規(guī)則:
- 一個(gè)文件代表一個(gè)模塊。
- ?可以用import module導(dǎo)入模塊,也可以用form module import member導(dǎo)入模塊的成員。
- 如果導(dǎo)入的是module,必須使用module.member進(jìn)行訪問(wèn);如果導(dǎo)入的member,可以直接訪問(wèn)member。
- 導(dǎo)入的module或member都會(huì)變成當(dāng)前module的member。
b.py
1 # coding=utf-8 2 3 print __name__ 4 5 def say_b(): 6 print "b"a.py
1 # coding=utf-8 2 3 import b 4 from b import * 5 6 print __name__ 7 8 def say_a(): 9 print "a"test.py
1 # coding=utf-8 2 3 import a 4 5 print __name__ 6 7 a.say_a(); 8 a.say_b(); 9 a.b.say_b()輸出
1 b 2 a 3 __main__ 4 a 5 b 6 b異常管理
1 # coding=utf-82 3 # 自定義異常4 class HappyException(Exception):5 pass6 7 # 引發(fā)和捕獲異常8 try:9 raise HappyException 10 except: 11 print("HappyException") 12 13 try: 14 raise HappyException() 15 except: 16 print("HappyException") 17 18 # 捕獲多種異常 19 try: 20 raise HappyException 21 except (HappyException, TypeError): 22 print("HappyException") 23 24 # 重新引發(fā)異常 25 try: 26 try: 27 raise HappyException 28 except (HappyException, TypeError): 29 raise 30 except: 31 print("HappyException") 32 33 #訪問(wèn)異常實(shí)例 34 try: 35 raise HappyException("都是我的錯(cuò)") 36 except (HappyException, TypeError), e: 37 print(e) 38 39 #按類(lèi)型捕獲 40 try: 41 raise HappyException 42 except HappyException: 43 print("HappyException") 44 except TypeError: 45 print("TypeError") 46 47 #全面捕獲 48 try: 49 raise HappyException 50 except: 51 print("HappyException") 52 53 #沒(méi)有異常的else 54 try: 55 pass 56 except: 57 print("HappyException") 58 else: 59 print("沒(méi)有異常") 60 61 #總會(huì)執(zhí)行的final 62 try: 63 pass 64 except: 65 print("HappyException") 66 else: 67 print("沒(méi)有異常") 68 finally: 69 print("總會(huì)執(zhí)行")面向?qū)ο?/h2>
先上一張圖
幾個(gè)規(guī)則:
?示例
1 # coding=utf-82 3 __metaclass__ = type4 5 # 類(lèi)型定義6 # 實(shí)例方法必的第一個(gè)參數(shù)代表類(lèi)型實(shí)例,類(lèi)似其他語(yǔ)言的this。7 class Animal:8 name = "未知" # 屬性定義。9 10 def __init__(self, name): #構(gòu)造方法定義。 11 self.name = name 12 13 def getName(self): # 實(shí)例方法定義。 14 return self.name 15 16 def setName(self, value): 17 self.name = value 18 19 print(Animal.name) # 未知 20 print(Animal.__dict__["name"]) # 未知 21 22 animal = Animal("狗狗") 23 print(animal.name) # 狗狗 24 print(animal.__dict__["name"]) # 狗狗 25 print(Animal.name) # 未知 26 print(Animal.__dict__["name"]) # 未知 27 print(animal.__class__.name) # 未知 28 print(animal.__class__.__dict__["name"]) # 未知 1 # 類(lèi)型定義中的代碼會(huì)執(zhí)行,是一個(gè)獨(dú)立的作用域。 2 class TestClass: 3 print("類(lèi)型定義中") #類(lèi)型定義中綁定方法和未綁定方法
1 class TestClass:2 def method(self):3 print("測(cè)試方法")4 5 test = TestClass()6 print(TestClass.method) #<unbound method TestClass.method>7 print(test.method) #<bound method TestClass.method of <__main__.TestClass object at 0x021B46D0>>8 9 TestClass.method(test) #測(cè)試方法 10 test.method() #測(cè)試方法綁定方法已經(jīng)綁定了對(duì)象示例,調(diào)用的時(shí)刻不用也不能傳入self參數(shù)了。
注:使用對(duì)象訪問(wèn)實(shí)例方法為何會(huì)返回綁定方法?這個(gè)還得等到學(xué)完“魔法方法”才能解釋,內(nèi)部其實(shí)是攔截對(duì)方法成員的訪問(wèn),返回了一個(gè)Callable對(duì)象。
私有成員
1 # 私有成員 2 class TestClass: 3 __private_property = 1 4 5 def __private_method(): 6 pass 7 8 print(TestClass.__dict__) # {'__module__': '__main__', '_TestClass__private_method': <function __private_method at 0x0212B970>, '_TestClass__private_property': 1難怪訪問(wèn)不了了,名稱(chēng)已經(jīng)被修改了,增加了訪問(wèn)的難度而已。
多重繼承
1 #多重繼承2 class Base1:3 pass4 5 class Base2:6 pass7 8 class Child(Base2, Base1):9 pass 10 11 child = Child() 12 print(isinstance(child, Child)) # True 13 print(isinstance(child, Base2)) # True 14 print(isinstance(child, Base1)) # True如果繼承的多個(gè)類(lèi)型之間有重名的成員,左側(cè)的基類(lèi)優(yōu)先級(jí)要高,上例子Base2會(huì)勝出。
接口那里去了,鴨子類(lèi)型比接口更好用。
1 class TestClass1:2 def say(self):3 print("我是鴨子1")4 5 class TestClass2:6 def say(self):7 print("我是鴨子2")8 9 def duck_say(duck): 10 duck.say() 11 12 duck_say(TestClass1()) # 我是鴨子1 13 duck_say(TestClass2()) # 我是鴨子2調(diào)用父類(lèi)
1 # 調(diào)用父類(lèi)2 class Base:3 def say(self):4 print("Base")5 6 class Child(Base):7 def say(self):8 Base.say(self)9 super(Child, self).say() 10 print("Child") 11 12 child = Child() 13 child.say()魔法方法
詳細(xì)內(nèi)容參考:http://www.rafekettler.com/magicmethods.html。
對(duì)象構(gòu)造相關(guān):__new__、__init__、__del__。
1 from os.path import join2 3 class FileObject:4 '''Wrapper for file objects to make sure the file gets closed on deletion.'''5 6 def __init__(self, filepath='~', filename='sample.txt'):7 # open a file filename in filepath in read and write mode8 self.file = open(join(filepath, filename), 'r+')9 10 def __del__(self): 11 self.file.close() 12 del self.file運(yùn)算符重載:所有運(yùn)算符都能重載。
1 class Word(str):2 '''Class for words, defining comparison based on word length.'''3 4 def __new__(cls, word):5 # Note that we have to use __new__. This is because str is an immutable6 # type, so we have to initialize it early (at creation)7 if ' ' in word:8 print "Value contains spaces. Truncating to first space."9 word = word[:word.index(' ')] # Word is now all chars before first space 10 return str.__new__(cls, word) 11 12 def __gt__(self, other): 13 return len(self) > len(other) 14 15 def __lt__(self, other): 16 return len(self) < len(other) 17 18 def __ge__(self, other): 19 return len(self) >= len(other) 20 21 def __le__(self, other): 22 return len(self) <= len(other) 23 24 print(Word("duan") > Word("wei"))屬性訪問(wèn)。
1 class AccessCounter:2 '''A class that contains a value and implements an access counter.3 The counter increments each time the value is changed.'''4 5 def __init__(self, value):6 super(AccessCounter, self).__setattr__('counter', 0)7 super(AccessCounter, self).__setattr__('value', value)8 9 def __setattr__(self, name, value): 10 if name == 'value': 11 super(AccessCounter, self).__setattr__('counter', self.counter + 1) 12 # Make this unconditional. 13 # If you want to prevent other attributes to be set, raise AttributeError(name) 14 super(AccessCounter, self).__setattr__(name, value) 15 16 def __delattr__(self, name): 17 if name == 'value': 18 super(AccessCounter, self).__setattr__('counter', self.counter + 1) 19 super(AccessCounter, self).__delattr__(name)集合實(shí)現(xiàn)。
1 class FunctionalList:2 '''A class wrapping a list with some extra functional magic, like head,3 tail, init, last, drop, and take.'''4 5 def __init__(self, values=None):6 if values is None:7 self.values = []8 else:9 self.values = values 10 11 def __len__(self): 12 return len(self.values) 13 14 def __getitem__(self, key): 15 # if key is of invalid type or value, the list values will raise the error 16 return self.values[key] 17 18 def __setitem__(self, key, value): 19 self.values[key] = value 20 21 def __delitem__(self, key): 22 del self.values[key] 23 24 def __iter__(self): 25 return iter(self.values) 26 27 def __reversed__(self): 28 return FunctionalList(reversed(self.values)) 29 30 def append(self, value): 31 self.values.append(value) 32 def head(self): 33 # get the first element 34 return self.values[0] 35 def tail(self): 36 # get all elements after the first 37 return self.values[1:] 38 def init(self): 39 # get elements up to the last 40 return self.values[:-1] 41 def last(self): 42 # get last element 43 return self.values[-1] 44 def drop(self, n): 45 # get all elements except first n 46 return self.values[n:] 47 def take(self, n): 48 # get first n elements 49 return self.values[:n]可調(diào)用對(duì)象,像方法一樣調(diào)用對(duì)象。
1 class Entity:2 '''Class to represent an entity. Callable to update the entity's position.'''3 4 def __init__(self, size, x, y):5 self.x, self.y = x, y6 self.size = size7 8 def __call__(self, x, y):9 '''Change the position of the entity.''' 10 self.x, self.y = x, y 11 print(x, y) 12 13 entity = Entity(5, 1, 1) 14 entity(2, 2)資源管理
1 class Closer:2 def __enter__(self):3 return self4 5 def __exit__(self, exception_type, exception_val, trace):6 print("清理完成")7 return True;8 9 with Closer() as closer: 10 pass對(duì)象描述符。
1 class Meter(object):2 '''Descriptor for a meter.'''3 4 def __init__(self, value=0.0):5 self.value = float(value)6 def __get__(self, instance, owner):7 return self.value8 def __set__(self, instance, value):9 self.value = float(value) 10 11 class Foot(object): 12 '''Descriptor for a foot.''' 13 14 def __get__(self, instance, owner): 15 return instance.meter * 3.2808 16 def __set__(self, instance, value): 17 instance.meter = float(value) / 3.2808 18 19 class Distance(object): 20 '''Class to represent distance holding two descriptors for feet and 21 meters.''' 22 meter = Meter() 23 foot = Foot()Mixin(也叫摻入)
摻入模塊:playable.py
1 # coding=utf-8 2 3 def paly(self): 4 print("游戲中...")摻入目標(biāo)模塊:test.py
1 # coding=utf-8 2 3 class Animal: 4 from playable import paly 5 6 animal = Animal() 7 animal.paly() # 游戲中...Open Class(打開(kāi)類(lèi)型,從新定義成員)
1 #coding:utf-82 3 class TestClass:4 def method1(self):5 print("方法1")6 7 def method2(self):8 print("方法2")9 10 TestClass.method2 = method2 11 12 test = TestClass() 13 test.method1() # 方法1 14 test.method2() # 方法2Meta Programming(元編程)
1 TestClass = type("TestClass", (object,), { 2 "say": lambda self : print("你好啊") 3 }) 4 5 test = TestClass() 6 test.say() 1 def getter(name):2 def getterMethod(self):3 return self.__getattribute__(name)4 return getterMethod5 6 def setter(name):7 def setterMethod(self, value):8 self.__setattr__(name, value)9 return setterMethod 10 11 class TestClass: 12 getName = getter("name") 13 setName = setter("name") 14 15 test = TestClass() 16 test.setName("段光偉") 17 print(test.getName())AOP(面向切面編程)
內(nèi)容比較多,單獨(dú)寫(xiě)了一篇文章:http://www.cnblogs.com/happyframework/p/3260233.html。
備注
Python在作用域方面非常接近Javascript,類(lèi)型和對(duì)象系統(tǒng)也有幾份相似(雖然Javascript是基于原型的),Javascript、PHP、Python和Ruby這幾門(mén)語(yǔ)言交叉學(xué)習(xí)會(huì)帶來(lái)意想不到的收獲。
轉(zhuǎn)載于:https://www.cnblogs.com/clarke/p/5898504.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專(zhuān)家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
以上是生活随笔為你收集整理的Python:Python学习总结的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 隐函数画图with R
- 下一篇: CSS优先级算法是如何计算?