数据库

小小星号创奇迹:一个字符就能改变你编写Python代码的方式

时间:2010-12-5 17:23:32  作者:数据库   来源:域名  查看:  评论:0
内容摘要:本文转载自公众号“读芯术”(ID:AI_Discovery)。Python以句法简单、简洁而闻名,只需掌握简单的英语就能理解其代码。对初学者来说极具吸引力,它没有声明,没有花哨的字符或者奇怪的句法。正

本文转载自公众号“读芯术”(ID:AI_Discovery)。小小星号写

Python以句法简单、创奇简洁而闻名,字符只需掌握简单的变编英语就能理解其代码。对初学者来说极具吸引力,小小星号写它没有声明,创奇没有花哨的字符字符或者奇怪的句法。正因如此,变编Python才得以风靡全球。小小星号写

除此之外,创奇Python还具备一些很酷的字符特点,比如装饰器和列表解析。变编这些特点确实能创造奇迹,小小星号写但*也值得这一美名,创奇小小字符能带来翻天覆地的字符变化。

先从一个小技巧开始:

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 [ ]: 

这是合并字典的超简单方法!你能明显看出,我仅用了几个星号就将字典结合了起来,服务器租用我接下来会一一解释。

星号在哪些地方发挥作用?

除了众所周知的乘法作用,星号还能让你轻松完成一些重要任务,例如解包。一般来说,你可以使用星号来解包可迭代对象,也能对双向可迭代对象(就像字典一样)进行双重解包。

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 

解包的力量

不要破坏别人的代码

大家也越来越理解这一点,但仍然有人没有遵守。开发者写出的每一个函数都有其特征。如果函数被改变,那么所有基于你的代码而撰写的代码都会被破坏。

图源:unsplash

我将介绍一种简单的方法,你可以为自己的函数增添更多功能性,同时也不会破坏其向后兼容性,高防服务器最后你会得到更多的模块化代码。

在你的代码中输入*args和**kwrags,它们会将所有输入都解包进函数。单星号针对标准的可迭代对象,双星号针对字典类的双向可迭代对象,举例说明:

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来接收之后的参数,并留到将来使用,同时也不会破坏你函数中原有的call函数。

星号是Python中很重要的一部分,但却常常被我们忽略。事实上,我们平常没有注意到的关键点还有很多,值得我们去一点点探索。

云南idc服务商
copyright © 2025 powered by 益强资讯全景  滇ICP备2023006006号-31sitemap