我的电报频道@pythonetc的提示和技巧,2019年11月
它是我的Telegram频道@pythonetc中有关Python和编程的一些新技巧和窍门。
←
以前的出版物 。
PATH
是一个环境变量,用于存储在其中查找可执行文件的路径。 当您要求外壳程序运行
ls
,外壳程序会在PATH中提供的所有路径中查找
ls
可执行文件。
$ echo $PATH /usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/v.pushtaev/.local/bin:/home/v.pushtaev/bin $ which ls /usr/bin/ls
在上面的示例中,路径在PATH中用
:
分隔。 无法转义:包含:的路径不能在
PATH
内部使用。
但是,并非对于所有操作系统都是如此。 在Python中,您可以使用
os.pathsep
为本地系统找到正确的分隔符:
Python 3.5.0 [...] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.pathsep ';'
os.pathsep
不能与
os.path.sep
混淆,后者是文件路径的分隔符:
>>> os.path.sep '/'
为了使正则表达式更具可读性,您可以使用
re.VERBOSE
标志。 它允许您在需要的地方使用多余的空格,并使用
#
符号添加注释:
import re URL_RE = re.compile(r''' ^ (https?):// (www[.])? ( (?: [^.]+[.] )+ ( [^/]+ ) # TLD ) (/.*) $ ''', re.VERBOSE) m = URL_RE.match('https://www.pythonetc.com/about/') schema, www, domain, tld, path = m.groups() has_www: bool = bool(www) print(f'schema={schema}, has_www={has_www}') print(f'domain={domain}, tld={tld}') print(f'path={path}')
re.X
是
re.VERBOSE
的别名。
complex
是
complex
的Python内置类型:
>>> complex(1, 2).real 1.0 >>> abs(complex(3, 4)) 5.0 >>> complex(1, 2) == complex(1, -2).conjugate() True >>> str(complex(2, -3)) '(2-3j)'
但是,由于Python具有用于复数的文字,因此无需直接使用它:
>>> (3 + 4j).imag 4.0 >>> not (3 + 4j) False >>> (-3 - 4j) + (2 - 2j) (-1-6j)
a : b : c
表示法仅可用于在括号内定义
slice(a, b, c)
:
>>> [1, 2, 3, 4, 5][0:4:2] [1, 3] >>> [1, 2, 3, 4, 5][slice(0, 4, 2)] [1, 3]
如果要将切片对象作为参数传递给函数,则必须显式定义它:
def multislice(slc, *iterables): return [i[slc] for i in iterables] print(multislice( slice(2, 6, 2), [1, 2, 3, 4, 5, 6, 7], [2, 4, 2, 4, 2, 4, 2], ))
这是将此类函数转换为支持
[a : b : c]
:
from functools import partial class SliceArgDecorator: def __init__(self, f): self._f = f def __getitem__(self, slc): return partial(self._f, slc) slice_arg = SliceArgDecorator @slice_arg def multislice(slc, *iterables): return [i[slc] for i in iterables] print(multislice[2:6:2]( [1, 2, 3, 4, 5, 6, 7], [2, 4, 2, 4, 2, 4, 2], ))
__getattribute__
是一个功能强大的工具,可让您在适当的时候轻松使用委派模式。 这是您添加与不可比较对象可比的功能的方式:
class CustomEq: def __init__(self, orig, *, key): self._orig = orig self._key = key def __lt__(self, other): return self._key(self) < self._key(other) def __getattribute__(self, name): if name in {'_key', '_orig', '__lt__'}: return super().__getattribute__(name) return getattr(self._orig, name) class User: def __init__(self, user_id): self._user_id = user_id def get_user_id(self): return self._user_id def comparable(obj, *, key): return CustomEq(obj, key=key) user1 = comparable(User(1), key=lambda u: u.get_user_id()) user2 = comparable(User(2), key=lambda u: u.get_user_id()) print(user2 > user1)