@Pythonetc编译,2019年11月


我的@pythonetc feed中提供了一系列新的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.pathsepos.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.Xre.VERBOSE的别名。



complexcomplex的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) # True print(user2 < user1) # False print(user2.get_user_id()) # 2 

Source: https://habr.com/ru/post/zh-CN480138/


All Articles