Python3中可能不会用到的10个功能!但是能让你的代码更简洁直观( 二 )


class Armor:def __init__(self, armor: float, description: str, level: int = 1): self.armor = armor self.level = level self.description = descriptiondef power(self) -> float: return self.armor * self.levelarmor = Armor(5.2, “Common armor.”, 2) armor.power() # 10.4print(armor) # <__main__.Armor object at 0x7fc4800e2cf8>使用数据类实现相同功能的Armor 。
from dataclasses import dataclass@dataclass class Armor: armor: float description: str level: int = 1def power(self) -> float: return self.armor * self.levelarmor = Armor(5.2, “Common armor.”, 2) armor.power() # 10.4print(armor) # Armor(armor=5.2, description=’Common armor.’, level=2)8.隐式命名空间包(3.3+)构建Python代码的方法之一是在软件包中(带有__init__.py文件的文件夹) 。下面的示例由Python的官方文档提供 。
sound/Top-level package__init__.pyInitialize the sound packageformats/Subpackage for file format conversions__init__.py wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py …effects/Subpackage for sound effects__init__.py echo.py surround.py reverse.py …filters/Subpackage for filters__init__.py equalizer.py vocoder.py karaoke.py …在Python 2中,上方的每个文件夹都必须具有__init__.py文件,该文件将该文件夹转换为Python包 。在Python 3中,一旦引入了隐式命名空间包,就不再需要这些文件 。
隐式命名空间包官方文档:https://www.python.org/dev/peps/pep-0420/
sound/Top-level package__init__.pyInitialize the sound packageformats/Subpackage for file format conversionswavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py …effects/Subpackage for sound effectsecho.py surround.py reverse.py …filters/Subpackage for filtersequalizer.py vocoder.py karaoke.py …注意:如果你认真观察的话,就会发现它并不像我在本节中所指出的那样简单,它来自正式的PEP 420规范—常规软件包仍然需要 __init__.py,将其从文件夹结构中删除会将其转变为本地名称空间带有附加限制的软件包 。
9.数字文字中的下划线(3.6+)Python3.6提供了一种很好的方法,通过在数字中启用下划线,允许读取数字文本 。这可以用来演示,例如:千位、十六进制和二进制数 。
cost = 10_000 print(f’Cost: {cost}’) # Cost: 10000hex_flag = 0xDAFE_FFF8 print(f’Hex flag: {hex_flag}’) # Hex flag: 3674144760binary = 0b_0011_1001 print(f’Binary: {binary}’) # Binary: 57Python 3.6通过使数字成为下划线来提供一种允许读取数字文字的绝佳方法 。例如,它可以用于演示:千位、十六进制和二进制数 。
10.赋值表达式-“walrus运算符”(3.8+)在Python的最新版本中,引入了walrus运算符,它能够对表达式进行变量赋值 。如果你想在代码中引用表达式,并在代码中保存一两行代码,那么它会非常有用 。
animals = [‘dog’, ‘lion’, ‘bear’, ‘tiger’]for animal in animals: if (len_animal := len(animal)) > 4: print(f’The animal “{animal}” has “{len_animal}”, letters!’)# The animal “tiger” has “5”, letters!总结可能我上面总结的内容还够不完整,如果你也了解一些我们不常用但是非常有效果的Python功能,欢迎在评论区告诉我们~ 希望以上内容能告诉你以前不知道的Python 3功能,并能让你写出更流畅,更直观的代码 。

Python3中可能不会用到的10个功能!但是能让你的代码更简洁直观

文章插图
 
 




推荐阅读