小小星號創(chuàng)奇跡:一個字符就能改變你編寫Python代碼的方式
本文轉(zhuǎn)載自公眾號“讀芯術(shù)”(ID:AI_Discovery)。
Python以句法簡單、簡潔而聞名,只需掌握簡單的英語就能理解其代碼。對初學(xué)者來說極具吸引力,它沒有聲明,沒有花哨的字符或者奇怪的句法。正因如此,Python才得以風(fēng)靡全球。
除此之外,Python還具備一些很酷的特點,比如裝飾器和列表解析。這些特點確實能創(chuàng)造奇跡,但*也值得這一美名,小小字符能帶來翻天覆地的變化。
先從一個小技巧開始:
- In [1]:
- first_dict= {'key1': 'hello', 'key2': 'world'}
- second_dict= {'key3': 'whats', 'key4': 'up'}
- In [2]:
- #joins the dicts
- combined_dict= {**first_dict, **second_dict}
- combined_dict
- Out[2]:
- {'key1': 'hello', 'key2': 'world', 'key3':'whats', 'key4': 'up'}
- In [ ]:
這是合并字典的超簡單方法!你能明顯看出,我僅用了幾個星號就將字典結(jié)合了起來,我接下來會一一解釋。
星號在哪些地方發(fā)揮作用?
除了眾所周知的乘法作用,星號還能讓你輕松完成一些重要任務(wù),例如解包。一般來說,你可以使用星號來解包可迭代對象,也能對雙向可迭代對象(就像字典一樣)進行雙重解包。
- In [7]:
- # unpackingan iterable
- [xfor x inrange(100)] == [*range(100)]
- Out[7]:
- True
- In [8]:
- #unpkacing dict keys
- d = {'key1': 'A'}
- list(d.keys()) == [*d]
- Out[8]:
- True
- In [9]:
- #unpacking whole dict
- d == {**d}
- Out[9]:
- True
解包的力量
不要破壞別人的代碼
大家也越來越理解這一點,但仍然有人沒有遵守。開發(fā)者寫出的每一個函數(shù)都有其特征。如果函數(shù)被改變,那么所有基于你的代碼而撰寫的代碼都會被破壞。
圖源:unsplash
我將介紹一種簡單的方法,你可以為自己的函數(shù)增添更多功能性,同時也不會破壞其向后兼容性,最后你會得到更多的模塊化代碼。
在你的代碼中輸入*args和**kwrags,它們會將所有輸入都解包進函數(shù)。單星號針對標準的可迭代對象,雙星號針對字典類的雙向可迭代對象,舉例說明:
- In [1]:
- defversion1(a, b):
- print(a)
- print(b)
- In [2]:
- version1(4,5)
- 4
- 5
- In [3]:
- #code breaks
- version1(4,5,6)
- ---------------------------------------------------------------------------
- TypeError Traceback(most recent call last)
- <ipython-input-3-b632c039a799> in<module>
- 1# code breaks
- ----> 2 version1(4,5,6)
- TypeError: version1() takes 2 positionalarguments but 3 were given
- In [4]:
- defversion2(a, b, *args):
- print(a)
- print(b)
- # new function.
- if args:
- for c in args:
- print(c)
- In [5]:
- version2(1,2,3,4,5)
- 1
- 2
- 3
- 4
- 5
- In [6]:
- #code breaks
- version2(1,2,3,4,5, Extra=10)
- ---------------------------------------------------------------------------
- TypeError Traceback(most recent call last)
- <ipython-input-6-748b0aef9e5d>in <module>
- 1 # code breaks
- ----> 2 version2(1,2,3,4,5, Extra=10)
- TypeError: version2() got an unexpectedkeyword argument 'Extra'
- In [7]:
- defversion3(a, b , *args, **kwrags):
- print(a)
- print(b)
- # new function.
- if args:
- for c in args:
- print(c)
- if kwrags:
- for key, value inzip(kwrags.keys(), kwrags.values()):
- print(key,':', value)
- In [8]:
- version3(1,2,3,4,5, Extra=10)
- 1
- 2
- 3
- 4
- 5
- Extra : 10
- In [ ]:
工作代碼和破解代碼
這個例子展示了如何使用args和kwargs來接收之后的參數(shù),并留到將來使用,同時也不會破壞你函數(shù)中原有的call函數(shù)。
星號是Python中很重要的一部分,但卻常常被我們忽略。事實上,我們平常沒有注意到的關(guān)鍵點還有很多,值得我們?nèi)ヒ稽c點探索。