电报频道_我的电报频道@pythonetc的提示和技巧,2019年10月
程序员文章站
2022-03-09 22:53:03
...
电报频道
It is a new selection of tips and tricks about Python and programming from my ********-channel @pythonetc.
这是我的********频道@pythonetc中有关Python和编程的一些新技巧和窍门。
←
← Previous publications以前的出版物
If you want to iterate over several iterables at once, you can use the
如果要一次迭代多个可迭代对象,可以使用
zip
function (it has nothing to do with ZIP file format):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}')
Output:
输出:
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
A generator can be stopped. You can explicitly call
发电机可以停止。 您可以显式调用
g.close()
but usually garbage collector does that for you. Once g.close()
但通常垃圾回收器会为您执行此操作。 调用close
is called, the close
, GeneratorExit
is raised at the point where the generator function was paused:GeneratorExit
将在生成器功能暂停的位置升高: def gen():
try:
yield 1
yield 2
finally:
print('END')
g = gen()
print(next(g)) # prints '1'
g.close() # prints 'END'
Mind three things. First, you can’t yield values while handling
注意三件事。 首先,在处理
GeneratorExit
:GeneratorExit
无法产生值: def gen():
try:
yield 1
finally:
yield 3
g = gen()
next(g)
g.close() # RuntimeError
Second, the exception is not raised if a generator is not yet started, but the generator still becomes stopped:
其次,如果尚未启动生成器,则不会引发异常,但是生成器仍会停止:
def gen():
try:
yield 1
finally:
print('END')
g = gen()
g.close() # nothing
print(list(g)) # prints '[]'
Third,
第三,如果生成器已经完成,则
close
does nothing if a generator is already finished:close
不执行任何操作: def gen():
try:
yield 1
yield 2
finally:
print('END')
g = gen()
print(list(g))
print('Closing now')
g.close()
# END
# [1, 2]
# Closing now
f-strings allow you to specify the width for the printed value as well as other format specifiers:
f字符串允许您指定打印值的宽度以及其他格式说明符:
>>> x = 42
>>> f'{x:5}+{x:15f}'
' 42+ 42.000000'
They can also contain evaluated expressions which can be useful when width is unknown upfront:
它们还可以包含评估表达式,这些表达式在宽度未知的情况下很有用:
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)
Output:
输出:
Eleven. Return and Revert 2010
Wilderness 2013
The Menagerie Inside 2015
Evaporate 2018
If your class is derived from another, the metaclass of your class have to be also derived from the metaclass of that class:
如果您的类是从另一个类派生的,则您的类的元类也必须从该类的元类派生:
from collections import UserDict
from abc import ABCMeta
# ABCMeta is a metaclass of UserDict
class MyDictMeta(ABCMeta):
def __new__(cls, name, bases, dct):
return super().__new__(cls, name, bases, dct)
class MyDict(UserDict, metaclass=MyDictMeta):
pass
It may be a good idea to get the metaclass of that other class automatically:
自动获取该其他类的元类可能是一个好主意:
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__
allows you to modify an object right after the creation. If you want to control what is created you should use __init__
允许您在创建后立即修改对象。 如果要控制创建的内容,则应改用__new__
instead:__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)
电报频道
上一篇: Java实战个人博客系统的实现流程