前言
Python 3.7 將于今年夏天發布,Python 3.7 中將會有許多新東西:
各種字符集的改進 對注釋的推遲評估 以及對dataclass的支持最激動人心的新功能之一是 dataclass 裝飾器。
什么是 Data Class
大多數 Python 開發人員編寫過很多像下面這樣的類:
class MyClass: def __init__(self, var_a, var_b): self.var_a = var_a self.var_b = var_b
dataclass 可以為簡單的情況自動生成方法,例如,一個__init__接受這些參數并將其分配給自己,之前的小例子可以重寫為:
@dataclassclass MyClass: var_a: str var_b: str
那么通過一個例子來看看如何使用吧
星球大戰 API
可以使用 requests 從星球大戰 API 獲取資源:
response = requests.get('https://swapi.co/api/films/1/')dictionary = response.json()讓我們來看看 dictionary (簡化過)的結果:
{ 'characters': ['https://swapi.co/api/people/1/',… ], 'created': '2014-12-10T14:23:31.880000Z', 'director': 'George Lucas', 'edited': '2015-04-11T09:46:52.774897Z', 'episode_id': 4, 'opening_crawl': 'It is a period of civil war./r/n … ', 'planets': ['https://swapi.co/api/planets/2/', … ], 'producer': 'Gary Kurtz, Rick McCallum', 'release_date': '1977-05-25', 'species': ['https://swapi.co/api/species/5/',…], 'starships': ['https://swapi.co/api/starships/2/',…], 'title': 'A New Hope', 'url': 'https://swapi.co/api/films/1/', 'vehicles': ['https://swapi.co/api/vehicles/4/',…]封裝 API
為了正確地封裝一個 API,我們應該創建一個用戶可以在其應用程序中使用的對象,因此,在Python 3.6 中定義一個對象來包含requests對 /films/endpoint的響應:
class StarWarsMovie: def __init__(self, title: str, episode_id: int, opening_crawl: str, director: str, producer: str, release_date: datetime, characters: List[str], planets: List[str], starships: List[str], vehicles: List[str], species: List[str], created: datetime, edited: datetime, url: str ): self.title = title self.episode_id = episode_id self.opening_crawl= opening_crawl self.director = director self.producer = producer self.release_date = release_date self.characters = characters self.planets = planets self.starships = starships self.vehicles = vehicles self.species = species self.created = created self.edited = edited self.url = url if type(self.release_date) is str: self.release_date = dateutil.parser.parse(self.release_date) if type(self.created) is str: self.created = dateutil.parser.parse(self.created) if type(self.edited) is str: self.edited = dateutil.parser.parse(self.edited)
仔細的讀者可能已經注意到這里有一些重復的代碼。
這是使用 dataclass 裝飾器的經典案例,我們需要創建一個主要用來保存數據的類,只需一點驗證,所以讓我們來看看我們需要修改什么。
新聞熱點
疑難解答