原文作者:zzir
Python 語法糖
\壳鹤,換行連接
s = ''
s += 'a' + \
'b' + \
'c'
n = 1 + 2 + \
3
# 6
while魔吐,for 循環(huán)外的 else
如果 while 循環(huán)正常結(jié)束(沒有break退出)就會執(zhí)行else弯汰。
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”)
zip() 并行迭代
a = [1,2,3]
b = ['one','two','three']
list(zip(a,b))
# [(1, 'one'), (2, 'two'), (3, 'three’)]
列表推導(dǎo)式
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]
字典推導(dǎo)式
{ key_exp : value_exp fro expression in iterable }
#查詢每個字母出現(xiàn)的次數(shù)。
strs = 'Hello World'
s = { k : strs.count(k) for k in set(strs) }
集合推導(dǎo)式
{expression for expression in iterable }
元組沒有推導(dǎo)式
本以為元組推導(dǎo)式是列表推導(dǎo)式改成括號窗宦,后來發(fā)現(xiàn)那個 生成器推導(dǎo)式赦颇。
生成器推導(dǎo)式
>>> num = ( x for x in range(5) )
>>> num
...:<generator object <genexpr> at 0x7f50926758e0>
函數(shù)
函數(shù)關(guān)鍵字參數(shù),默認(rèn)參數(shù)值
def do(a=0,b,c)
return (a,b,c)
do(a=1,b=3,c=2)
函數(shù)默認(rèn)參數(shù)值在函數(shù)定義時已經(jīng)計算出來赴涵,而不是在程序運行時媒怯。
列表字典等可變數(shù)據(jù)類型不可以作為默認(rèn)參數(shù)值。
def buygy(arg, result=[]):
result.append(arg)
print(result)
changed:
def nobuygy(arg, result=None):
if result == None:
result = []
result.append(arg)
print(result)
# or
def nobuygy2(arg):
result = []
result.append(arg)
print(result)
*args 收集位置參數(shù)
def do(*args):
print(args)
do(1,2,3)
(1,2,3,'d’)
**kwargs
收集關(guān)鍵字參數(shù)
def do(**kwargs):
print(kwargs)
do(a=1,b=2,c='la')
# {'c': 'la', 'a': 1, 'b': 2}
lamba 匿名函數(shù)
a = lambda x: x*x
a(4)
# 16
生成器
生成器是用來創(chuàng)建Python序列的一個對象髓窜∩劝可以用它迭代序列而不需要在內(nèi)存中創(chuàng)建和存儲整個序列欺殿。
通常,生成器是為迭代器產(chǎn)生數(shù)據(jù)的鳖敷。
生成器函數(shù)函數(shù)和普通函數(shù)類似脖苏,返回值使用 yield 而不是 return 。
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>
裝飾器
有時需要在不改變源代碼的情況下修改已經(jīng)存在的函數(shù)定踱。
裝飾器實質(zhì)上是一個函數(shù)帆阳,它把函數(shù)作為參數(shù)輸入到另一個函數(shù)。 舉個栗子:
# 一個裝飾器
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)
# 函數(shù)器前加裝飾器名字
@document_it
def add_ints(a, b):
return a + b
可以使用多個裝飾器屋吨,多個裝飾由內(nèi)向外向外順序執(zhí)行。
命名空間和作用域
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 提供了兩個獲取命名空間內(nèi)容的函數(shù) 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__)
異常處理,try...except
只有錯誤發(fā)生時才執(zhí)行的代碼资锰。 舉個栗子:
>>> 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
沒有自定異常類型使用任何錯誤敢课。
獲取異常對象,except exceptiontype as name
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
命令行參數(shù)
命令行參數(shù)
python文件:
import sys
print(sys.argv)
PPrint()友好輸出
與print()用法相同,輸出結(jié)果像是列表字典時會不同鞭盟。
類
子類super()調(diào)用父類方法
舉個栗子:
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’
self.__name 保護私有特性
class Person():
def __init__(self, name):
self.__name = name
a = Person('me')
>>> a.name
... AttributeError: 'Person' object has no attribute '__name'
# 小技巧
a._Person__name
實例方法( instance method )
實例方法圾结,以self作為第一個參數(shù),當(dāng)它被調(diào)用時齿诉,Python會把調(diào)用該方法的的對象作為self參數(shù)傳入筝野。
class A():
count = 2
def __init__(self): # 這就是一個實例方法
A.count += 1
類方法 @classmethod
class A():
count = 2
def __init__(self):
A.count += 1
@classmethod
def hello(h):
print("hello",h.count)
注意,使用h.count(類特征)粤剧,而不是self.count(對象特征)歇竟。
靜態(tài)方法 @staticmethod
class A():
@staticmethod
def hello():
print("hello, staticmethod")
>>> A.hello()
創(chuàng)建即用,優(yōu)雅不失風(fēng)格抵恋。
特殊方法(sqecial method)
一個普通方法:
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
'{} {} {}'.format(11,22,33)
# 11 22 33
'{2:2d} {0:-10d} {1:10d}'.format(11,22,33)
# :后面是格式標(biāo)識符
# 33 11 22
'{a} {c}'.format(a=11,b=22,c=33)