它是我的Telegram频道@pythonetc中有关Python和编程的一些新技巧和窍门。
←
以前的出版物如果要一次迭代多个可迭代对象,则可以使用
zip
函数(与ZIP文件格式无关):
from datetime import timedelta names = [ 'Eleven. Return and Revert', 'Wilderness', 'The Menagerie Inside', 'Evaporate', ] years = [ 2010, 2013, 2015, 2018, ] durations = [ timedelta(minutes=57, seconds=38), timedelta(minutes=48, seconds=5), timedelta(minutes=46, seconds=34), timedelta(minutes=43, seconds=25), ] print('Midas Fall LPs:') for name, year, duration in zip( names, years, durations ): print(f' * {name} ({year}) — {duration}')
输出:
Midas Fall LPs: * Eleven. Return and Revert (2010) — 0:57:38 * Wilderness (2013) — 0:48:05 * The Menagerie Inside (2015) — 0:46:34 * Evaporate (2018) — 0:43:25
发电机可以停止。 您可以显式调用
g.close()
但通常垃圾收集器会为您执行此操作。 调用
close
,
GeneratorExit
将在生成器功能暂停的位置升高:
def gen(): try: yield 1 yield 2 finally: print('END') g = gen() print(next(g))
注意三件事。 首先,在处理
GeneratorExit
无法产生值:
def gen(): try: yield 1 finally: yield 3 g = gen() next(g) g.close()
其次,如果尚未启动生成器,则不会引发异常,但是生成器仍会停止:
def gen(): try: yield 1 finally: print('END') g = gen() g.close()
第三,如果生成器已经完成,则
close
不执行任何操作:
def gen(): try: yield 1 yield 2 finally: print('END') g = gen() print(list(g)) print('Closing now') g.close()
f字符串允许您指定打印值的宽度以及其他格式说明符:
>>> x = 42 >>> f'{x:5}+{x:15f}' ' 42+ 42.000000'
它们还可以包含评估表达式,这些表达式在宽度未知的情况下很有用:
def print_table(matrix): cols_width = [ max(len(str(row[col])) for row in matrix) for col in range(len(matrix[0])) ] for row in matrix: for i, cell in enumerate(row): print( f'{cell:{cols_width[i]}} ', end='' ) print() albums = [ ['Eleven. Return and Revert', 2010], ['Wilderness', 2013], ['The Menagerie Inside', 2015], ['Evaporate', 2018], ] print_table(albums)
输出:
Eleven. Return and Revert 2010 Wilderness 2013 The Menagerie Inside 2015 Evaporate 2018
如果您的类是从另一个类派生的,则您的类的元类也必须从该类的元类派生:
from collections import UserDict from abc import ABCMeta
自动获取其他类的元类可能是一个好主意:
def create_my_dict_class(parents): class MyDictMeta(*[type(c) for c in parents]): def __new__(cls, name, bases, dct): return super().__new__(cls, name, bases, dct) class MyDict(*parents, metaclass=MyDictMeta): pass MyDict = create_my_dict_class((UserDict,))
__init__
允许您在创建后立即修改对象。 如果要控制创建的内容,则应使用
__new__
:
from typing import Tuple, Dict from cached_property import cached_property class Numbers: _LOADED: Dict[Tuple[int, ...], 'Numbers'] = {} def __new__(cls, ints: Tuple[int, ...]): if ints not in cls._LOADED: obj = super().__new__(cls) cls._LOADED[ints] = obj return cls._LOADED[ints] def __init__(self, ints: Tuple[int, ...]): self._ints = ints @cached_property def biggest(self): print('calculating...') return max(self._ints) print(Numbers((4, 3, 5)).biggest) print(Numbers((4, 3, 5)).biggest) print(Numbers((4, 3, 6)).biggest)