因为Python2的官方维护期即将结束,愈来愈多的Python项目从Python2切换到了Python3。但是,在实际的工做中,我发现好多人都是在用Python2的思惟去写Python3的代码,Python3给咱们提供了不少新的、很方便的特性,能够帮助咱们快速的编写代码。python
在Python里面,咱们常常使用format函数来格式化字符串,例如:缓存
user = "Jane Doe" action = "buy" log_message = 'User {} has logged in and did an action {}.'.format( user, action ) print(log_message) 输出:User Jane Doe has logged in and did an action buy.
Python3里面提供了一个更加灵活方便的方法来格式化字符串,叫作f-strings。上面的代码能够这样实现:app
user = "Jane Doe" action = "buy" log_message = f'User {user} has logged in and did an action {action}.' print(log_message) 输出: User Jane Doe has logged in and did an action buy.
f-strings这个功能太方便了,可是对于文件路劲这样的字符串,Python还提供了更加方便的处理方法。Pathlib是Python3提供的一个处理文件路劲的库。例如:函数
from pathlib import Path root = Path('post_sub_folder') print(root) 输出结果: post_sub_folder path = root / 'happy_user' # 输出绝对路劲 print(path.resolve()) 输出结果:/root/post_sub_folder/happy_user
静态与动态类型是软件工程中的一个热门话题,每一个人都有不一样的见解,Python做为一个动态类型语言,在Python3中也提供了Type hinting功能,例如:post
def sentence_has_animal(sentence: str) -> bool: return "animal" in sentence sentence_has_animal("Donald had a farm without animals") # True
Python3提供的Enum类让你很容就能实现一个枚举类型:优化
from enum import Enum, auto class Monster(Enum): ZOMBIE = auto() WARRIOR = auto() BEAR = auto() print(Monster.ZOMBIE) 输出: Monster.ZOMBIE
Python3的Enum还支持比较和迭代。ui
for monster in Monster: print(monster) 输出: Monster.ZOMBIE Monster.WARRIOR Monster.BEAR
缓存是如今的软件领域常常使用的技术,Python3提供了一个lru_cache装饰器,来让你更好的使用缓存。下面有个实例:spa
import time def fib(number: int) -> int: if number == 0: return 0 if number == 1: return 1 return fib(number-1) + fib(number-2) start = time.time() fib(40) print(f'Duration: {time.time() - start}s') # Duration: 30.684099674224854s
如今咱们可使用lru_cache来优化咱们上面的代码,下降代码执行时间。code
from functools import lru_cache @lru_cache(maxsize=512) def fib_memoization(number: int) -> int: if number == 0: return 0 if number == 1: return 1 return fib_memoization(number-1) + fib_memoization(number-2) start = time.time() fib_memoization(40) print(f'Duration: {time.time() - start}s') # Duration: 6.866455078125e-05s
废话很少说,直接上代码,文档在这orm
head, *body, tail = range(5) print(head, body, tail) 输出: 0 [1, 2, 3] 4 py, filename, *cmds = "python3.7 script.py -n 5 -l 15".split() print(py) print(filename) print(cmds) 输出:python3.7 script.py ['-n', '5', '-l', '15'] first, _, third, *_ = range(10) print(first, third) 输出: 0 2
Python3提供data class装饰器来让咱们更好的处理数据对象,而不用去实现 init__() 和 __repr() 方法。假设以下的代码:
class Armor: def __init__(self, armor: float, description: str, level: int = 1): self.armor = armor self.level = level self.description = description def power(self) -> float: return self.armor * self.level armor = Armor(5.2, "Common armor.", 2) armor.power() # 10.4 print(armor) # <__main__.Armor object at 0x7fc4800e2cf8>
使用data class实现上面功能的代码,这么写:
from dataclasses import dataclass @dataclass class Armor: armor: float description: str level: int = 1 def power(self) -> float: return self.armor * self.level armor = Armor(5.2, "Common armor.", 2) armor.power() # 10.4 print(armor) # Armor(armor=5.2, description='Common armor.', level=2)
一般状况下,Python经过把代码打成包(在目录中加入__init__.py实现)来复用,官方给的示例以下:
sound/ Top-level package __init__.py Initialize the sound package formats/ 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
在Python2里,如上的目录结构,每一个目录都必须有__init__.py文件,一遍其余模块调用目录下的python代码,在Python3里,经过 Implicit Namespace Packages但是不使用__init__.py文件
sound/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions wavread.py wavwrite.py aiffread.py aiffwrite.py auread.py auwrite.py ... effects/ Subpackage for sound effects echo.py surround.py reverse.py ... filters/ Subpackage for filters equalizer.py vocoder.py karaoke.py
这篇文章只列出了一下部分Python3的新功能,我但愿这篇文章向您展现了部分您之前不知道的Python 3新功能,而且但愿能帮助您编写更清晰,更直观的代码。