s = '' s += 'a' + \ 'b' + \ 'c' n = 1 + 2 + \ 3 # 6
若是 while 循環正常結束(沒有break退出)就會執行else。python
num = [1,2,3,4] mark = 0 while mark < len(num): n = num[mark] if n % 2 == 0: print(n) # break mark += 1 else: print("done")
a = [1,2,3] b = ['one','two','three'] list(zip(a,b)) # [(1, 'one'), (2, 'two'), (3, 'three')]
x = [num for num in range(6)] # [0, 1, 2, 3, 4, 5] y = [num for num in range(6) if num % 2 == 0] # [0, 2, 4] # 多層嵌套 rows = range(1,4) cols = range(1,3) for i in rows: for j in cols: print(i,j) # 同 rows = range(1,4) cols = range(1,3) x = [(i,j) for i in rows for j in cols]
{ key_exp : value_exp fro expression in iterable }express
#查詢每一個字母出現的次數。 strs = 'Hello World' s = { k : strs.count(k) for k in set(strs) }
{expression for expression in iterable }app
本覺得元組推導式是列表推導式改爲括號,後來發現那個 生成器推導式。函數
>>> num = ( x for x in range(5) ) >>> num ...:<generator object <genexpr> at 0x7f50926758e0>
def do(a=0,b,c) return (a,b,c) do(a=1,b=3,c=2)
函數默認參數值在函數定義時已經計算出來,而不是在程序運行時。
列表字典等可變數據類型不能夠做爲默認參數值。ui
def buygy(arg, result=[]): result.append(arg) print(result)
changed:.net
def nobuygy(arg, result=None): if result == None: result = [] result.append(arg) print(result) # or def nobuygy2(arg): result = [] result.append(arg) print(result)
def do(*args): print(args) do(1,2,3) (1,2,3,'d')
def do(**kwargs): print(kwargs) do(a=1,b=2,c='la') # {'c': 'la', 'a': 1, 'b': 2}
a = lambda x: x*x a(4) # 16
生成器是用來建立Python序列的一個對象。能夠用它迭代序列而不須要在內存中建立和存儲整個序列。
一般,生成器是爲迭代器產生數據的。命令行
生成器函數函數和普通函數相似,返回值使用 yield 而不是 return 。code
def my_range(first=0,last=10,step=1): number = first while number < last: yield number number += step >>> my_range() ... <generator object my_range at 0x7f02ea0a2bf8>
有時須要在不改變源代碼的狀況下修改已經存在的函數。
裝飾器實質上是一個函數,它把函數做爲參數輸入到另外一個函數。
舉個栗子:orm
# 一個裝飾器 def document_it(func): def new_function(*args, **kwargs): print("Runing function: ", func.__name__) print("Positional arguments: ", args) print("Keyword arguments: ", kwargs) result = func(*args, **kwargs) print("Result: " ,result) return result return new_function # 人工賦值 def add_ints(a, b): return a + b cooler_add_ints = document_it(add_ints) #人工對裝飾器賦值 cooler_add_ints(3,5) # 函數器前加裝飾器名字 @document_it def add_ints(a, b): return a + b
能夠使用多個裝飾器,多個裝飾由內向外向外順序執行。對象
a = 1234 def test(): print("a = ",a) # True #### a = 1234 def test(): a = a -1 #False print("a = ",a)
能夠使用全局變量 global a
。
a = 1234 def test(): global a a = a -1 #True print("a = ",a)
Python 提供了兩個獲取命名空間內容的函數local()
global()
Python 保留用法。
舉個栗子:
def amazing(): '''This is the amazing. Hello world''' print("The function named: ", amazing.__name__) print("The function docstring is: \n", amazing.__doc__)
只有錯誤發生時才執行的代碼。
舉個栗子:
>>> l = [1,2,3] >>> index = 5 >>> l[index] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: list index out of range
再試下:
>>> l = [1,2,3] >>> index = 5 >>> try: ... l[index] ... except: ... print("Error: need a position between 0 and", len(l)-1, ", But got", index) ... Error: need a position between 0 and 2 , But got 5
沒有自定異常類型使用任何錯誤。
short_list = [1,2,3] while 1: value = input("Position [q to quit]? ") if value == 'q': break try: position = int(value) print(short_list[position]) except IndexError as err: print("Bad index: ", position) except Exception as other: print("Something else broke: ", other)
異常是一個類。類 Exception
的子類。
class UppercaseException(Exception): pass words = ['a','b','c','AA'] for i in words: if i.isupper(): raise UppercaseException(i) # error Traceback (most recent call last): File "<stdin>", line 3, in <module> __main__.UppercaseException: AA
python文件:
import sys print(sys.argv)
與print()用法相同,輸出結果像是列表字典時會不一樣。
舉個栗子:
class Person(): def __init__(self, name): self.name = name class email(Person): def __init__(self, name, email): super().__init__(name) self.email = email a = email('me', 'me@me.me') >>> a.name ... 'me' >>> a.email ... 'me@me.me'
class Person(): def __init__(self, name): self.__name = name a = Person('me') >>> a.name ... AttributeError: 'Person' object has no attribute '__name' # 小技巧 a._Person__name
實例方法,以self做爲第一個參數,當它被調用時,Python會把調用該方法的的對象做爲self參數傳入。
class A(): count = 2 def __init__(self): # 這就是一個實例方法 A.count += 1
class A(): count = 2 def __init__(self): A.count += 1 @classmethod def hello(h): print("hello",h.count)
注意,使用h.count
(類特徵),而不是self.count
(對象特徵)。
class A(): @staticmethod def hello(): print("hello, staticmethod") >>> A.hello()
建立即用,優雅不失風格。
一個普通方法:
class word(): def __init__(self, text): self.text = text def equals(self, word2): #注意 return self.text.lower() == word2.text.lower() a1 = word('aa') a2 = word('AA') a3 = word('33') a1.equals(a2) # True
使用特殊方法:
class word(): def __init__(self, text): self.text = text def __eq__(self, word2): #注意,使用__eq__ return self.text.lower() == word2.text.lower() a1 = word('aa') a2 = word('AA') a3 = word('33') a1 == a2 # True
其餘還有:
*方法名* *使用* __eq__(self, other) self == other __ne__(self, other) self != other __lt__(self, other) self < other __gt__(self, other) self > other __le__(self, other) self <= other __ge__(self, other) self >= other __add__(self, other) self + other __sub__(self, other) self - other __mul__(self, other) self * other __floordiv__(self, other) self // other __truediv__(self, other) self / other __mod__(self, other) self % other __pow__(self, other) self ** other __str__(self) str(self) __repr__(self) repr(self) __len__(self) len(self)
'%-10d | %-10f | %10s | %10x' % ( 1, 1.2, 'ccc', 0xf ) # '1 | 1.200000 | ccc | 33'
'{} {} {}'.format(11,22,33) # 11 22 33 '{2:2d} {0:-10d} {1:10d}'.format(11,22,33) # :後面是格式標識符 # 33 11 22 '{a} {b} {c}'.format(a=11,b=22,c=33)