مجموعة جديدة من نصائح Python والبرمجة من خلال موجز pythonetc الخاص بي.
←
المنشورات السابقةPATH
هو متغير بيئة يخزن المسارات التي يتم من خلالها البحث عن الملفات القابلة للتنفيذ. عندما تطلب من shell تنفيذ
ls
، فإنه يبحث أولاً عن
ls
القابل للتنفيذ في جميع المسارات المحددة في
PATH
.
$ 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
باستخدام
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(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)