你應該使用Python3裏的這些新特性

概述

因爲Python2的官方維護期即將結束,愈來愈多的Python項目從Python2切換到了Python3。但是,在實際的工做中,我發現好多人都是在用Python2的思惟去寫Python3的代碼,Python3給咱們提供了不少新的、很方便的特性,能夠幫助咱們快速的編寫代碼。python

f-strings (3.6+)

在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.

Pathlib (3.4+)

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

Type hinting (3.5+)

靜態與動態類型是軟件工程中的一個熱門話題,每一個人都有不一樣的見解,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

Enumerations (3.4+)

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

Built-in LRU cache (3.2+)

緩存是如今的軟件領域常常使用的技術,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

Extended iterable unpacking (3.0+)

廢話很少說,直接上代碼,文檔在這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

Data classes (3.7+)

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)

Implicit namespace packages (3.3+)

一般狀況下,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新功能,而且但願能幫助您編寫更清晰,更直觀的代碼。

相關文章
相關標籤/搜索