Ikhtisar¶
>>>
¶The default Python prompt of the interactive shell. Often seen for code examples which can be executed interactively in the interpreter.
...
¶Dapat mengacu ke:
The default Python prompt of the interactive shell when entering the code for an indented code block, when within a pair of matching left and right delimiters (parentheses, square brackets, curly braces or triple quotes), or after specifying a decorator.
Konstanta
Ellipsis
bawaan.
- kelas basis abstrak¶
Абстрактні базові класи доповнюють duck-typing, надаючи спосіб для визначення інтерфейсів, коли інші методи, такі як
hasattr()
, були б незручними або дещо неправильними (наприклад, з магічними методами). ABC вводить віртуальні підкласи, що є класами, які не успадковуються від класу, але все ще можуть розпізнватися за допомогоюisinstance()
таissubclass()
; дивіться документацію модуляabc
. Python має багато вбудованх ABC для різних структур(у модуліcollections.abc
), чисел (у модуліnumbers
), потоків (у модуліio
) , шукачів імпортів і завантажувачів (у модуліimportlib.abc
). Ви можете створювати власні азбуки за допомогою модуляabc
.- annotate function¶
A function that can be called to retrieve the annotations of an object. This function is accessible as the
__annotate__
attribute of functions, classes, and modules. Annotate functions are a subset of evaluate functions.- anotasi¶
Etykieta powiązana ze zmienną, atrybutem klasy lub parametrem funkcji lub wartością zwracaną, używana zgodnie z konwencją jako type hint.
Annotations of local variables cannot be accessed at runtime, but annotations of global variables, class attributes, and functions can be retrieved by calling
annotationlib.get_annotations()
on modules, classes, and functions, respectively.See variable annotation, function annotation, PEP 484, PEP 526, and PEP 649, which describe this functionality. Also see Annotations Best Practices for best practices on working with annotations.
- argumen¶
Значення, яке передається function (або method) під час виклику функції. Існує два види аргументів:
keyword argument: аргумент, якому передує ідентифікатор (наприклад,
name=
) під час виклику функції або передається як значення в словнику перед яким**
. Наприклад,3
і5
є ключовими аргументами в наступних викликахcomplex()
:complex(real=3, imag=5) complex(**{'real': 3, 'imag': 5})
positional argument: аргумент, який не є аргументом ключового слова. Позиційні аргументи можуть з’являтися на початку списку аргументів і/або передаватися як елементи iterable, яким передує
*
. Наприклад,3
і5
є позиційними аргументами в наступних викликах:complex(3, 5) complex(*(3, 5))
Аргументи призначаються названим локальним змінним у тілі функції. Перегляньте розділ Calls для правил, що регулюють це призначення. Синтаксично будь-який вираз можна використовувати для представлення аргументу; обчислене значення присвоюється локальній змінній.
Дивіться також parameter глосарій, питання FAQ про різницю між аргументами та параметрами, і PEP 362.
- manajer konteks asinkron¶
An object which controls the environment seen in an
async with
statement by defining__aenter__()
and__aexit__()
methods. Introduced by PEP 492.- pembangkit asinkron¶
Функція, яка повертає asynchronous generator iterator. Це виглядає як функція співпрограми, визначена за допомогою
async def
, за винятком того, що вона містить виразиyield
для створення серії значень, які можна використовувати в цикліasync for
.Зазвичай відноситься до функції асинхронного генератора, але в деяких контекстах може посилатися на ітератор асинхронного генератора. У випадках, коли передбачуване значення не є зрозумілим, використання повних термінів дозволяє уникнути двозначності.
Функція асинхронного генератора може містити вирази
await
, а також операториasync for
іasync with
.- iterator generator asinkron¶
An object created by an asynchronous generator function.
This is an asynchronous iterator which when called using the
__anext__()
method returns an awaitable object which will execute the body of the asynchronous generator function until the nextyield
expression.Each
yield
temporarily suspends processing, remembering the execution state (including local variables and pending try-statements). When the asynchronous generator iterator effectively resumes with another awaitable returned by__anext__()
, it picks up where it left off. See PEP 492 and PEP 525.- асинхронний ітерований¶
An object, that can be used in an
async for
statement. Must return an asynchronous iterator from its__aiter__()
method. Introduced by PEP 492.- iterator asinkron¶
An object that implements the
__aiter__()
and__anext__()
methods.__anext__()
must return an awaitable object.async for
resolves the awaitables returned by an asynchronous iterator's__anext__()
method until it raises aStopAsyncIteration
exception. Introduced by PEP 492.- attached thread state¶
A thread state that is active for the current OS thread.
When a thread state is attached, the OS thread has access to the full Python C API and can safely invoke the bytecode interpreter.
Unless a function explicitly notes otherwise, attempting to call the C API without an attached thread state will result in a fatal error or undefined behavior. A thread state can be attached and detached explicitly by the user through the C API, or implicitly by the runtime, including during blocking C calls and by the bytecode interpreter in between calls.
On most builds of Python, having an attached thread state implies that the caller holds the GIL for the current interpreter, so only one OS thread can have an attached thread state at a given moment. In free-threaded builds of Python, threads can concurrently hold an attached thread state, allowing for true parallelism of the bytecode interpreter.
- atribut¶
A value associated with an object which is usually referenced by name using dotted expressions. For example, if an object o has an attribute a it would be referenced as o.a.
It is possible to give an object an attribute whose name is not an identifier as defined by Names (identifiers and keywords), for example using
setattr()
, if the object allows it. Such an attribute will not be accessible using a dotted expression, and would instead need to be retrieved withgetattr()
.- menunggu¶
An object that can be used in an
await
expression. Can be a coroutine or an object with an__await__()
method. See also PEP 492.- BDFL¶
Доброзичливий диктатор на все життя (BDFL - Benevolent Dictator For Life), також відомий як Гвідо ван Россум, творець Python.
- berkas biner¶
A file object able to read and write bytes-like objects. Examples of binary files are files opened in binary mode (
'rb'
,'wb'
or'rb+'
),sys.stdin.buffer
,sys.stdout.buffer
, and instances ofio.BytesIO
andgzip.GzipFile
.Дивіться також text file для об’єкта файлу, здатного читати та записувати об’єкти
str
.- borrowed reference¶
In Python's C API, a borrowed reference is a reference to an object, where the code using the object does not own the reference. It becomes a dangling pointer if the object is destroyed. For example, a garbage collection can remove the last strong reference to the object and so destroy it.
Calling
Py_INCREF()
on the borrowed reference is recommended to convert it to a strong reference in-place, except when the object cannot be destroyed before the last usage of the borrowed reference. ThePy_NewRef()
function can be used to create a new strong reference.- байтоподібний об'єкт¶
Об’єкт, який підтримує Protokol Penampung Buffer і може експортувати буфер C-contiguous. Це включає всі об’єкти
bytes
,bytearray
іarray.array
, а також багато поширених об’єктівmemoryview
. Байтоподібні об'єкти можна використовувати для різних операцій, які працюють з двійковими даними; вони включають стиснення, збереження у бінарний файл і надсилання через сокет.Для деяких операцій двійкові дані повинні бути змінними. У документації вони часто називаються "байтоподібними об’єктами читання-запису". Приклади змінних буферних об’єктів включають
bytearray
іmemoryview
bytearray
. Інші операції вимагають, щоб двійкові дані зберігалися в незмінних об’єктах ("байтоподібні об’єкти лише для читання"); прикладами таких єbytes
іmemoryview
об’єктаbytes
.- bytecode¶
Вихідний код Python компілюється в байт-код, внутрішнє представлення програми Python в інтерпретаторі CPython. Байт-код також кешується у файлах
.pyc
, тому виконання того самого файлу відбувається швидше вдруге (можна уникнути перекомпіляції з вихідного коду в байт-код). Кажуть, що ця "проміжна мова" працює на virtual machine, яка виконує машинний код, що відповідає кожному байт-коду. Зауважте, що байт-коди не повинні працювати між різними віртуальними машинами Python, а також бути стабільними між випусками Python.Daftar instruksi-instruksi bytecode dapat ditemukan di dokumentasi pada the dis module.
- викликний¶
A callable is an object that can be called, possibly with a set of arguments (see argument), with the following syntax:
callable(argument1, argument2, argumentN)
A function, and by extension a method, is a callable. An instance of a class that implements the
__call__()
method is also a callable.- wywołanie zwrotne¶
Функція підпрограми, яка передається як аргумент для виконання в певний момент у майбутньому.
- kelas¶
Шаблон для створення користувальницьких об'єктів. Визначення класу зазвичай містять визначення методів, які працюють над екземплярами класу.
- змінна класу¶
Змінна, визначена в класі та призначена для зміни лише на рівні класу (тобто не в екземплярі класу).
- closure variable¶
A free variable referenced from a nested scope that is defined in an outer scope rather than being resolved at runtime from the globals or builtin namespaces. May be explicitly defined with the
nonlocal
keyword to allow write access, or implicitly defined if the variable is only being read.For example, in the
inner
function in the following code, bothx
andprint
are free variables, but onlyx
is a closure variable:def outer(): x = 0 def inner(): nonlocal x x += 1 print(x) return inner
Due to the
codeobject.co_freevars
attribute (which, despite its name, only includes the names of closure variables rather than listing all referenced free variables), the more general free variable term is sometimes used even when the intended meaning is to refer specifically to closure variables.- bilangan kompleks¶
Розширення відомої дійсної системи числення, у якій усі числа виражаються як сума дійсної та уявної частин. Уявні числа — це дійсні кратні уявної одиниці (квадратного кореня з
-1
), які часто пишутьсяi
в математиці абоj
в інженерії. Python має вбудовану підтримку комплексних чисел, які записуються з використанням цієї останньої нотації; уявна частина записується з суфіксомj
, наприклад,3+1j
. Щоб отримати доступ до комплексних еквівалентів модуляmath
, використовуйтеcmath
. Використання комплексних чисел є досить просунутою математичною функцією. Якщо ви не усвідомлюєте потреби в них, майже впевнено, що можете спокійно їх ігнорувати.- context¶
This term has different meanings depending on where and how it is used. Some common meanings:
The temporary state or environment established by a context manager via a
with
statement.The collection of keyvalue bindings associated with a particular
contextvars.Context
object and accessed viaContextVar
objects. Also see context variable.A
contextvars.Context
object. Also see current context.
- context management protocol¶
The
__enter__()
and__exit__()
methods called by thewith
statement. See PEP 343.- manajer konteks¶
An object which implements the context management protocol and controls the environment seen in a
with
statement. See PEP 343.- контекстна змінна¶
A variable whose value depends on which context is the current context. Values are accessed via
contextvars.ContextVar
objects. Context variables are primarily used to isolate state between concurrent asynchronous tasks.- суміжний¶
Буфер вважається безперервним, якщо він C-суміжний або Fortran безперервний. Нульвимірні буфери є суміжними на C і Fortran. В одновимірних масивах елементи повинні розташовуватися в пам’яті поруч один з одним у порядку зростання індексів, починаючи з нуля. У багатовимірних C-суміжних масивах останній індекс змінюється найшвидше під час відвідування елементів у порядку адреси пам’яті. Однак у безперервних масивах Fortran перший індекс змінюється найшвидше.
- coroutine¶
Співпрограми є більш узагальненою формою підпрограм. Підпрограми вводяться в одній точці і виходять з іншої. У співпрограми можна ввійти, вийти з них і відновити їх у багатьох різних точках. Їх можна реалізувати за допомогою оператора
async def
. Дивіться також PEP 492.- функція співпрограми¶
Функція, яка повертає об’єкт coroutine. Функція співпрограми може бути визначена оператором
async def
і може містити ключові словаawait
,async for
іasync with
. Їх представив PEP 492.- CPython¶
Канонічна реалізація мови програмування Python, яка розповсюджується на python.org. Термін "CPython" використовується, коли необхідно відрізнити цю реалізацію від інших, таких як Jython або IronPython.
- current context¶
The context (
contextvars.Context
object) that is currently used byContextVar
objects to access (get or set) the values of context variables. Each thread has its own current context. Frameworks for executing asynchronous tasks (seeasyncio
) associate each task with a context which becomes the current context whenever the task starts or resumes execution.- cyclic isolate¶
A subgroup of one or more objects that reference each other in a reference cycle, but are not referenced by objects outside the group. The goal of the cyclic garbage collector is to identify these groups and break the reference cycles so that the memory can be reclaimed.
- decorator¶
Функція, що повертає іншу функцію, зазвичай застосовується як перетворення функції за допомогою синтаксису
@wrapper
. Типовими прикладами для декораторів єclassmethod()
іstaticmethod()
.Синтаксис декоратора є просто синтаксичним цукром, наступні два визначення функції семантично еквівалентні:
def f(arg): ... f = staticmethod(f) @staticmethod def f(arg): ...
Така сама концепція існує для класів, але використовується там рідше. Перегляньте документацію щодо визначення функцій та визначення класів, щоб дізнатися більше про декоратори.
- deskryptor¶
Any object which defines the methods
__get__()
,__set__()
, or__delete__()
. When a class attribute is a descriptor, its special binding behavior is triggered upon attribute lookup. Normally, using a.b to get, set or delete an attribute looks up the object named b in the class dictionary for a, but if b is a descriptor, the respective descriptor method gets called. Understanding descriptors is a key to a deep understanding of Python because they are the basis for many features including functions, methods, properties, class methods, static methods, and reference to super classes.Для отримання додаткової інформації про методи дескрипторів див. Implementing Descriptors або Посібник з використання дескрипторів.
- dictionary¶
An associative array, where arbitrary keys are mapped to values. The keys can be any object with
__hash__()
and__eq__()
methods. Called a hash in Perl.- dictionary comprehension¶
Компактний спосіб обробки всіх або частини елементів у ітерації та повернення словника з результатами.
results = {n: n ** 2 for n in range(10)}
генерує словник, що містить ключn
, зіставлений зі значеннямn ** 2
. Дивіться Displays for lists, sets and dictionaries.- перегляд словника¶
Об’єкти, що повертаються з
dict.keys()
,dict.values()
іdict.items()
, називаються представленнями словника. Вони забезпечують динамічний перегляд словникових статей, що означає, що коли словник змінюється, перегляд відображає ці зміни. Щоб змусити перегляд словника стати повним списком, використовуйтеlist(dictview)
. Перегляньте Dictionary view objects.- docstring¶
A string literal which appears as the first expression in a class, function or module. While ignored when the suite is executed, it is recognized by the compiler and put into the
__doc__
attribute of the enclosing class, function or module. Since it is available via introspection, it is the canonical place for documentation of the object.- Качина типізація¶
Стиль програмування, який не дивиться на тип об’єкта, щоб визначити, чи має він правильний інтерфейс; замість цього метод або атрибут просто викликається або використовується ("Якщо він схожий на качку і крякає як качка, це має бути качка".) Підкреслюючи інтерфейси, а не конкретні типи, добре розроблений код покращує свою гнучкість, дозволяючи поліморфне заміщення. Duck-введення дозволяє уникнути тестів з використанням
type()
абоisinstance()
. (Однак зауважте, що качиний тип може бути доповнений абстрактними базовими класами.) Замість цього зазвичай використовуютьсяhasattr()
тести або EAFP програмування.- dunder¶
An informal short-hand for "double underscore", used when talking about a special method. For example,
__init__
is often pronounced "dunder init".- EAFP¶
Легше попросити вибачення, ніж дозволу (Easier to ask for forgiveness than permission). Цей поширений стиль кодування Python припускає існування дійсних ключів або атрибутів і перехоплює винятки, якщо припущення виявиться хибним. Цей чистий і швидкий стиль характеризується наявністю багатьох операторів
try
іexcept
. Техніка контрастує зі стилем LBYL, поширеним у багатьох інших мовах, таких як C.- evaluate function¶
A function that can be called to evaluate a lazily evaluated attribute of an object, such as the value of type aliases created with the
type
statement.- ekspresi¶
Частина синтаксису, яка може бути оцінена до певного значення. Іншими словами, вираз — це сукупність елементів виразу, таких як літерали, імена, доступ до атрибутів, оператори або виклики функцій, які повертають значення. На відміну від багатьох інших мов, не всі мовні конструкції є виразами. Існують також statements, які не можна використовувати як вирази, наприклад
while
. Присвоєння також є операторами, а не виразами.- modul tambahan¶
Модуль, написаний мовою C або C++, який використовує C API Python для взаємодії з ядром і кодом користувача.
- f-string¶
- f-strings¶
String literals prefixed with
f
orF
are commonly called "f-strings" which is short for formatted string literals. See also PEP 498.- objek berkas¶
An object exposing a file-oriented API (with methods such as
read()
orwrite()
) to an underlying resource. Depending on the way it was created, a file object can mediate access to a real on-disk file or to another type of storage or communication device (for example standard input/output, in-memory buffers, sockets, pipes, etc.). File objects are also called file-like objects or streams.Фактично існує три категорії файлових об’єктів: необроблені бінарні файли, буферизовані бінарні файли і текстові файли. Їхні інтерфейси визначені в модулі
io
. Канонічний спосіб створення файлового об’єкта – це використання функціїopen()
.- файлоподібний об'єкт¶
Синонім file object.
- filesystem encoding and error handler¶
Encoding and error handler used by Python to decode bytes from the operating system and encode Unicode to the operating system.
The filesystem encoding must guarantee to successfully decode all bytes below 128. If the file system encoding fails to provide this guarantee, API functions can raise
UnicodeError
.The
sys.getfilesystemencoding()
andsys.getfilesystemencodeerrors()
functions can be used to get the filesystem encoding and error handler.The filesystem encoding and error handler are configured at Python startup by the
PyConfig_Read()
function: seefilesystem_encoding
andfilesystem_errors
members ofPyConfig
.See also the locale encoding.
- wyszukiwarka¶
Об’єкт, який намагається знайти loader для модуля, який імпортується.
There are two types of finder: meta path finders for use with
sys.meta_path
, and path entry finders for use withsys.path_hooks
.See Finders and loaders and
importlib
for much more detail.- поділ поверху¶
Математичне ділення, яке округлюється до найближчого цілого числа. Оператор поділу підлоги –
//
. Наприклад, вираз11 // 4
обчислюється як2
на відміну від2,75
, яке повертає float true division. Зауважте, що(-11) // 4
є-3
, тому що це-2,75
, округлене униз. Дивіться PEP 238.- free threading¶
A threading model where multiple threads can run Python bytecode simultaneously within the same interpreter. This is in contrast to the global interpreter lock which allows only one thread to execute Python bytecode at a time. See PEP 703.
- free variable¶
Formally, as defined in the language execution model, a free variable is any variable used in a namespace which is not a local variable in that namespace. See closure variable for an example. Pragmatically, due to the name of the
codeobject.co_freevars
attribute, the term is also sometimes used as a synonym for closure variable.- fungsi¶
Серія операторів, які повертають певне значення абоненту. Йому також можна передати нуль або більше аргументів, які можуть бути використані під час виконання тіла. Дивіться також parameter, method і розділ Definisi fungsi.
- anotasi fungsi¶
annotation параметра функції або значення, що повертається.
Анотації функцій зазвичай використовуються для підказок типу: наприклад, ця функція має приймати два аргументи
int
і також має повертати значенняint
:def sum_two_numbers(a: int, b: int) -> int: return a + b
Синтаксис анотації функції пояснюється в розділі Definisi fungsi.
See variable annotation and PEP 484, which describe this functionality. Also see Annotations Best Practices for best practices on working with annotations.
- __future__¶
інструкція future,
from __future__ import <feature>
, вказує компілятору скомпілювати поточний модуль, використовуючи синтаксис або семантику, які стануть стандартними в майбутньому випуску Python. Модуль__future__
документує можливі значення feature. Імпортувавши цей модуль та оцінивши його змінні, ви можете побачити, коли нова функція була вперше додана до мови та коли вона стане (або стала) типовою:>>> import __future__ >>> __future__.division _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
- pengumpulan sampah¶
Процес звільнення пам'яті, коли вона більше не використовується. Python виконує збирання сміття за допомогою підрахунку посилань і циклічного збирача сміття, здатного виявляти та розривати цикли посилань. Збирачем сміття можна керувати за допомогою модуля
gc
.- pembangkit¶
Функція, яка повертає generator iterator. Це виглядає як звичайна функція, за винятком того, що вона містить вирази
yield
для створення серії значень, які можна використовувати в циклі for або які можна отримати по одному за допомогою функціїnext()
.Зазвичай відноситься до функції-генератора, але в деяких контекстах може посилатися на ітератор-генератор. У випадках, коли передбачуване значення не є зрозумілим, використання повних термінів дозволяє уникнути двозначності.
- ітератор генератора¶
Об’єкт, створений функцією generator.
Each
yield
temporarily suspends processing, remembering the execution state (including local variables and pending try-statements). When the generator iterator resumes, it picks up where it left off (in contrast to functions which start fresh on every invocation).- генераторний вираз¶
An expression that returns an iterator. It looks like a normal expression followed by a
for
clause defining a loop variable, range, and an optionalif
clause. The combined expression generates values for an enclosing function:>>> sum(i*i for i in range(10)) # sum of squares 0, 1, 4, ... 81 285
- fungsi generik¶
Функція, що складається з кількох функцій, які реалізують ту саму операцію для різних типів. Яку реалізацію слід використовувати під час виклику, визначається алгоритмом диспетчеризації.
Дивіться також запис глосарію single dispatch, декоратор
functools.singledispatch()
і PEP 443.- родовий тип¶
type, який можна параметризувати; зазвичай це клас-контейнер, наприклад
list
абоdict
. Використовується для підказок типу та анотацій.Для отримання додаткової інформації див. загальні типи псевдонімів, PEP 483, PEP 484, PEP 585 і модуль
typing
.- GIL¶
Lihat global interpreter lock.
- kunci interpreter global¶
Механізм, який використовується інтерпретатором CPython, щоб гарантувати, що лише один потік виконує bytecode Python за раз. Це спрощує реалізацію CPython, роблячи об’єктну модель (включно з критично важливими вбудованими типами, такими як
dict
) неявно захищеною від одночасного доступу. Блокування всього інтерпретатора полегшує багатопотоковість інтерпретатора за рахунок більшої частини паралелізму, який надають багатопроцесорні машини.However, some extension modules, either standard or third-party, are designed so as to release the GIL when doing computationally intensive tasks such as compression or hashing. Also, the GIL is always released when doing I/O.
As of Python 3.13, the GIL can be disabled using the
--disable-gil
build configuration. After building Python with this option, code must be run with-X gil=0
or after setting thePYTHON_GIL=0
environment variable. This feature enables improved performance for multi-threaded applications and makes it easier to use multi-core CPUs efficiently. For more details, see PEP 703.In prior versions of Python's C API, a function might declare that it requires the GIL to be held in order to use it. This refers to having an attached thread state.
- на основі хешу pyc¶
Файл кешу байт-коду, який використовує хеш, а не час останньої зміни відповідного вихідного файлу для визначення його дійсності. Перегляньте Cached bytecode invalidation.
- хешований¶
An object is hashable if it has a hash value which never changes during its lifetime (it needs a
__hash__()
method), and can be compared to other objects (it needs an__eq__()
method). Hashable objects which compare equal must have the same hash value.Хешування робить об’єкт придатним для використання як ключ словника та член набору, оскільки ці структури даних використовують хеш-значення внутрішньо.
Більшість незмінних вбудованих об’єктів Python можна хешувати; змінні контейнери (такі як списки або словники) не є; незмінні контейнери (такі як кортежі та заморожені набори) можна хешувати, лише якщо їх елементи хешуються. Об’єкти, які є екземплярами визначених користувачем класів, хешуються за замовчуванням. Усі вони порівнюються неоднаково (за винятком самих себе), і їх хеш-значення походить від їхнього
id()
.- IDLE¶
An Integrated Development and Learning Environment for Python. IDLE --- Python editor and shell is a basic editor and interpreter environment which ships with the standard distribution of Python.
- immortal¶
Immortal objects are a CPython implementation detail introduced in PEP 683.
If an object is immortal, its reference count is never modified, and therefore it is never deallocated while the interpreter is running. For example,
True
andNone
are immortal in CPython.Immortal objects can be identified via
sys._is_immortal()
, or viaPyUnstable_IsImmortal()
in the C API.- незмінний¶
Об’єкт із фіксованим значенням. До незмінних об’єктів належать числа, рядки та кортежі. Такий об'єкт не можна змінити. Якщо потрібно зберегти інше значення, потрібно створити новий об’єкт. Вони відіграють важливу роль у місцях, де потрібне постійне хеш-значення, наприклад, як ключ у словнику.
- шлях імпорту¶
Список розташувань (або записів шляху), у яких path based finder шукає модулі для імпорту. Під час імпорту цей список розташувань зазвичай надходить із
sys.path
, але для підпакетів він також може надходити з атрибута__path__
батьківського пакета.- import¶
Процес, за допомогою якого код Python в одному модулі стає доступним для коду Python в іншому модулі.
- importer¶
Об’єкт, який знаходить і завантажує модуль; як об’єкт finder, так і loader.
- interaktif¶
Python has an interactive interpreter which means you can enter statements and expressions at the interpreter prompt, immediately execute them and see their results. Just launch
python
with no arguments (possibly by selecting it from your computer's main menu). It is a very powerful way to test out new ideas or inspect modules and packages (rememberhelp(x)
). For more on interactive mode, see Mode Interaktif.- diinterpretasi¶
Python є інтерпретованою мовою, на відміну від скомпільованої, хоча відмінність може бути розмитою через наявність компілятора байт-коду. Це означає, що вихідні файли можна запускати безпосередньо без явного створення виконуваного файлу, який потім запускається. Інтерпретовані мови зазвичай мають коротший цикл розробки/налагодження, ніж скомпільовані, хоча їхні програми також працюють повільніше. Дивіться також interactive.
- вимкнення перекладача¶
Коли його попросять завершити роботу, інтерпретатор Python переходить у спеціальну фазу, де він поступово звільняє всі виділені ресурси, такі як модулі та різні критичні внутрішні структури. Він також робить кілька викликів до збирача сміття. Це може ініціювати виконання коду в визначених користувачем деструкторах або зворотних викликах weakref. Код, який виконується під час фази завершення роботи, може зіткнутися з різними винятками, оскільки ресурси, на які він покладається, можуть більше не функціонувати (поширеними прикладами є бібліотечні модулі або механізм попереджень).
Основною причиною вимкнення інтерпретатора є завершення виконання модуля
__main__
або сценарію, який виконується.- ітерований¶
An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as
list
,str
, andtuple
) and some non-sequence types likedict
, file objects, and objects of any classes you define with an__iter__()
method or with a__getitem__()
method that implements sequence semantics.Iterables can be used in a
for
loop and in many other places where a sequence is needed (zip()
,map()
, ...). When an iterable object is passed as an argument to the built-in functioniter()
, it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to calliter()
or deal with iterator objects yourself. Thefor
statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator, sequence, and generator.- iterator¶
An object representing a stream of data. Repeated calls to the iterator's
__next__()
method (or passing it to the built-in functionnext()
) return successive items in the stream. When no more data are available aStopIteration
exception is raised instead. At this point, the iterator object is exhausted and any further calls to its__next__()
method just raiseStopIteration
again. Iterators are required to have an__iter__()
method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as alist
) produces a fresh new iterator each time you pass it to theiter()
function or use it in afor
loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.Informasi lebih lanjut dapat ditemukan di Iterator Types.
Detail implementasi CPython: CPython does not consistently apply the requirement that an iterator define
__iter__()
. And also please note that the free-threading CPython does not guarantee the thread-safety of iterator operations.- fungsi kunci¶
Ключова функція або функція зіставлення — це виклик, який повертає значення, яке використовується для сортування або впорядкування. Наприклад,
locale.strxfrm()
використовується для створення ключа сортування, який враховує умови сортування для певної мови.Кілька інструментів у Python приймають ключові функції для керування тим, як елементи впорядковуються чи групуються. Серед них
min()
,max()
,sorted()
,list.sort()
,heapq.merge()
,heapq.nsmallest()
,heapq.nlargest()
іitertools.groupby()
.There are several ways to create a key function. For example. the
str.lower()
method can serve as a key function for case insensitive sorts. Alternatively, a key function can be built from alambda
expression such aslambda r: (r[0], r[2])
. Also,operator.attrgetter()
,operator.itemgetter()
, andoperator.methodcaller()
are three key function constructors. See the Sorting HOW TO for examples of how to create and use key functions.- argumen kata kunci¶
Lihat argument.
- lambda¶
Анонімна вбудована функція, що складається з одного expression, який обчислюється під час виклику функції. Синтаксис створення лямбда-функції такий:
лямбда [параметри]: вираз
- LBYL¶
Сім разів відміряй, один раз відріж. Цей стиль кодування явно перевіряє попередні умови перед здійсненням викликів або пошуку. Цей стиль контрастує з підходом EAFP і характеризується наявністю багатьох операторів
if
.У багатопоточному середовищі підхід LBYL може загрожувати введенням умов змагання між "дивлячим" і "стрибаючим". Наприклад, код
if key in mapping: return mapping[key]
може завершитися помилкою, якщо інший потік видаляє key із mapping після перевірки, але перед пошуком. Цю проблему можна вирішити за допомогою блокувань або використання підходу EAFP.- lexical analyzer¶
Formal name for the tokenizer; see token.
- list¶
A built-in Python sequence. Despite its name it is more akin to an array in other languages than to a linked list since access to elements is O(1).
- розуміння списку¶
Компактний спосіб обробки всіх або частини елементів у послідовності та повернення списку з результатами.
result = ['{:#04x}'.format(x) for x in range(256) if x % 2 == 0]
створює список рядків, що містять парні шістнадцяткові числа (0x..) у діапазон від 0 до 255. Реченняif
є необов’язковим. Якщо опущено, обробляються всі елементи в діапазоні (256).- ładowarka¶
An object that loads a module. It must define the
exec_module()
andcreate_module()
methods to implement theLoader
interface. A loader is typically returned by a finder. See also:- locale encoding¶
On Unix, it is the encoding of the LC_CTYPE locale. It can be set with
locale.setlocale(locale.LC_CTYPE, new_locale)
.On Windows, it is the ANSI code page (ex:
"cp1252"
).On Android and VxWorks, Python uses
"utf-8"
as the locale encoding.locale.getencoding()
can be used to get the locale encoding.See also the filesystem encoding and error handler.
- metoda magiczna¶
Неофіційний синонім слова special method.
- pemetaan¶
A container object that supports arbitrary key lookups and implements the methods specified in the
collections.abc.Mapping
orcollections.abc.MutableMapping
abstract base classes. Examples includedict
,collections.defaultdict
,collections.OrderedDict
andcollections.Counter
.- мета-шлях пошуку¶
finder, що повертається в результаті пошуку
sys.meta_path
. Засоби пошуку меташляхів пов’язані з засобами пошуку записів шляху, але відрізняються від них.Перегляньте
importlib.abc.MetaPathFinder
методи, які реалізують засоби пошуку меташляхів.- metaklasa¶
Клас класу. Визначення класу створюють назву класу, словник класу та список базових класів. Метаклас відповідає за отримання цих трьох аргументів і створення класу. Більшість об'єктно-орієнтованих мов програмування забезпечують реалізацію за замовчуванням. Що робить Python особливим, так це те, що можна створювати власні метакласи. Більшості користувачів цей інструмент ніколи не потрібен, але коли виникає потреба, метакласи можуть надати потужні та елегантні рішення. Вони використовувалися для реєстрації доступу до атрибутів, додавання потокової безпеки, відстеження створення об’єктів, реалізації одиночних елементів і багатьох інших завдань.
Informasi lebih lanjut dapat ditemukan di Metaclasses.
- metoda¶
Функція, яка визначена всередині тіла класу. Якщо викликати його як атрибут примірника цього класу, метод отримає об’єкт примірника як свій перший argument (який зазвичай називається
self
). Див. function і nested scope.- порядок вирішення методу¶
Method Resolution Order is the order in which base classes are searched for a member during lookup. See The Python 2.3 Method Resolution Order for details of the algorithm used by the Python interpreter since the 2.3 release.
- modul¶
Об’єкт, який є організаційною одиницею коду Python. Модулі мають простір імен, що містить довільні об’єкти Python. Модулі завантажуються в Python за допомогою процесу importing.
Lihat juga package.
- модуль спец¶
Простір імен, що містить пов’язану з імпортом інформацію, яка використовується для завантаження модуля. Екземпляр
importlib.machinery.ModuleSpec
.See also Module specs.
- MRO¶
Lihat method resolution order.
- мінливий¶
Змінні об’єкти можуть змінювати своє значення, але зберігають свій
id()
. Дивіться також immutable.- nazwana krotka¶
Термін "іменований кортеж" застосовується до будь-якого типу або класу, який успадковує кортеж і чиї індексовані елементи також доступні за допомогою іменованих атрибутів. Тип або клас також можуть мати інші особливості.
Кілька вбудованих типів є іменованими кортежами, включаючи значення, що повертаються
time.localtime()
іos.stat()
. Інший приклад:sys.float_info
:>>> sys.float_info[1] # indexed access 1024 >>> sys.float_info.max_exp # named field access 1024 >>> isinstance(sys.float_info, tuple) # kind of tuple True
Some named tuples are built-in types (such as the above examples). Alternatively, a named tuple can be created from a regular class definition that inherits from
tuple
and that defines named fields. Such a class can be written by hand, or it can be created by inheritingtyping.NamedTuple
, or with the factory functioncollections.namedtuple()
. The latter techniques also add some extra methods that may not be found in hand-written or built-in named tuples.- простір імен¶
Місце, де зберігається змінна. Простори імен реалізовані як словники. Існують локальні, глобальні та вбудовані простори імен, а також вкладені простори імен в об’єктах (у методах). Простори імен підтримують модульність, запобігаючи конфліктам імен. Наприклад, функції
builtins.open
іos.open()
відрізняються своїми просторами імен. Простори імен також сприяють читабельності та зручності обслуговування, пояснюючи, який модуль реалізує функцію. Наприклад, написанняrandom.seed()
абоitertools.islice()
дає зрозуміти, що ці функції реалізовані модулямиrandom
іitertools
відповідно.- пакет простору імен¶
A package which serves only as a container for subpackages. Namespace packages may have no physical representation, and specifically are not like a regular package because they have no
__init__.py
file.Namespace packages allow several individually installable packages to have a common parent package. Otherwise, it is recommended to use a regular package.
For more information, see PEP 420 and Namespace packages.
Lihat juga module.
- вкладена область¶
Можливість посилатися на змінну в охоплюючому визначенні. Наприклад, функція, визначена всередині іншої функції, може посилатися на змінні у зовнішній функції. Зауважте, що вкладені області за замовчуванням працюють лише для довідки, а не для призначення. Локальні змінні читають і записують у внутрішній області видимості. Так само глобальні змінні читають і записують у глобальний простір імен.
nonlocal
дозволяє писати у зовнішні області.- клас нового стилю¶
Old name for the flavor of classes now used for all class objects. In earlier Python versions, only new-style classes could use Python's newer, versatile features like
__slots__
, descriptors, properties,__getattribute__()
, class methods, and static methods.- objek¶
Будь-які дані зі станом (атрибути або значення) і визначеною поведінкою (методи). Також остаточний базовий клас будь-якого new-style class.
- optimized scope¶
A scope where target local variable names are reliably known to the compiler when the code is compiled, allowing optimization of read and write access to these names. The local namespaces for functions, generators, coroutines, comprehensions, and generator expressions are optimized in this fashion. Note: most interpreter optimizations are applied to all scopes, only those relying on a known set of local and nonlocal variable names are restricted to optimized scopes.
- paket¶
A Python module which can contain submodules or recursively, subpackages. Technically, a package is a Python module with a
__path__
attribute.Дивіться також regular package і namespace package.
- parameter¶
Іменована сутність у визначенні function (або методу), яка визначає argument (або в деяких випадках аргументи), які функція може прийняти. Є п'ять типів параметрів:
positional-or-keyword: визначає аргумент, який можна передати позиційно або як аргумент ключового слова. Це тип параметра за замовчуванням, наприклад foo і bar у наступному:
def func(foo, bar=None): ...
positional-only: визначає аргумент, який можна надати лише за позицією. Лише позиційні параметри можна визначити, включивши символ
/
у список параметрів визначення функції після них, наприклад posonly1 і posonly2 у наступному:def func(posonly1, posonly2, /, positional_or_keyword): ...
keyword-only: визначає аргумент, який можна надати лише за ключовим словом. Параметри, що містять лише ключове слово, можна визначити, включивши один змінний позиційний параметр або голий
*
у список параметрів визначення функції перед ними, наприклад kw_only1 і kw_only2 у наступному:def func(arg, *, kw_only1, kw_only2): ...
var-positional: вказує, що можна надати довільну послідовність позиційних аргументів (на додаток до будь-яких позиційних аргументів, уже прийнятих іншими параметрами). Такий параметр можна визначити, додавши перед назвою параметра
*
, наприклад args у наступному:def func(*args, **kwargs): ...
var-keyword: вказує, що можна надати довільну кількість аргументів ключових слів (на додаток до будь-яких аргументів ключових слів, які вже прийняті іншими параметрами). Такий параметр можна визначити, додавши перед назвою параметра
**
, наприклад kwargs у прикладі вище.
Параметри можуть вказувати як необов’язкові, так і обов’язкові аргументи, а також значення за умовчанням для деяких необов’язкових аргументів.
Дивіться також argument глосарій, питання FAQ про різницю між аргументами та параметрами,
inspect.Parameter
клас, Definisi fungsi розділ та PEP 362.- запис шляху¶
Єдине розташування на import path, до якого path based finder звертається, щоб знайти модулі для імпорту.
- шукач запису шляху¶
finder, що повертається викликом на
sys.path_hooks
(тобто path entry hook), який знає, як знаходити модулі за допомогою path entry.Перегляньте
importlib.abc.PathEntryFinder
методи, які реалізують засоби пошуку запису шляху.- гачок входу шляху¶
A callable on the
sys.path_hooks
list which returns a path entry finder if it knows how to find modules on a specific path entry.- пошук на основі шляху¶
Один із стандартних мета-шляхів пошуку, який шукає import path для модулів.
- шляхоподібний об’єкт¶
Об'єкт, що представляє шлях до файлової системи. Шляховий об’єкт – це або
str
, абоbytes
об’єкт, що представляє шлях, або об’єкт, що реалізує протоколos.PathLike
. Об’єкт, який підтримує протоколos.PathLike
, можна перетворити на шлях файлової системиstr
абоbytes
шляхом виклику функціїos.fspath()
;os.fsdecode()
іos.fsencode()
можна використовувати, щоб гарантувати результатstr
абоbytes
відповідно. Представлений PEP 519.- PEP¶
Пропозиція вдосконалення Python. PEP — це проектний документ, який надає інформацію спільноті Python або описує нову функцію для Python або його процеси чи середовище. Публічні діячі повинні надавати стислу технічну специфікацію та обґрунтування запропонованих функцій.
PEP мають бути основними механізмами для пропонування основних нових функцій, для збору інформації спільноти щодо проблеми та для документування проектних рішень, які увійшли в Python. Автор PEP відповідає за формування консенсусу в спільноті та документування особливих думок.
Lihat PEP 1.
- porsi¶
Набір файлів в одному каталозі (можливо, збережених у файлі zip), які входять до пакету простору імен, як визначено в PEP 420.
- позиційний аргумент¶
Lihat argument.
- тимчасовий API¶
Попередній API — це той, який був навмисно виключений із гарантій зворотної сумісності стандартної бібліотеки. Хоча суттєвих змін у таких інтерфейсах не очікується, доки вони позначені як тимчасові, зворотні несумісні зміни (аж до видалення інтерфейсу включно) можуть відбутися, якщо розробники ядра вважають це за потрібне. Такі зміни не будуть внесені безоплатно — вони відбудуться лише за умови виявлення серйозних фундаментальних недоліків, які були пропущені до включення API.
Навіть для тимчасових API зворотні несумісні зміни розглядаються як "вирішення останньої інстанції" — все одно будуть зроблені всі спроби знайти зворотно сумісне вирішення будь-яких виявлених проблем.
Цей процес дозволяє стандартній бібліотеці продовжувати розвиватися з часом, не блокуючи проблемні помилки проектування протягом тривалих періодів часу. Дивіться PEP 411 для більш детальної інформації.
- тимчасовий пакет¶
Lihat provisional API.
- Python 3000¶
Псевдонім для рядка випусків Python 3.x (придуманий давно, коли випуск версії 3 був чимось у віддаленому майбутньому). Це також скорочено "Py3k".
- Pythoniczny¶
Ідея або фрагмент коду, який точно відповідає найпоширенішим ідіомам мови Python, а не реалізує код за допомогою концепцій, спільних для інших мов. Наприклад, поширена ідіома в Python полягає в тому, щоб перебирати всі елементи ітерованого за допомогою оператора
for
. Багато інших мов не мають такого типу конструкції, тому люди, які не знайомі з Python, іноді замість цього використовують числовий лічильник:for i in range(len(food)): print(food[i])
На відміну від очищувача, метод Pythonic:
for piece in food: print(piece)
- nama yang memenuhi syarat¶
Назва з крапками, що вказує "шлях" від глобальної області видимості модуля до класу, функції або методу, визначеного в цьому модулі, як визначено в PEP 3155. Для функцій і класів верхнього рівня кваліфіковане ім’я збігається з ім’ям об’єкта:
>>> class C: ... class D: ... def meth(self): ... pass ... >>> C.__qualname__ 'C' >>> C.D.__qualname__ 'C.D' >>> C.D.meth.__qualname__ 'C.D.meth'
Коли використовується для позначення модулів, повне ім’я означає весь шлях до модуля, розділений крапками, включаючи будь-які батьківські пакети, напр.
email.mime.text
:>>> import email.mime.text >>> email.mime.text.__name__ 'email.mime.text'
- jumlah referensi¶
The number of references to an object. When the reference count of an object drops to zero, it is deallocated. Some objects are immortal and have reference counts that are never modified, and therefore the objects are never deallocated. Reference counting is generally not visible to Python code, but it is a key element of the CPython implementation. Programmers can call the
sys.getrefcount()
function to return the reference count for a particular object.In CPython, reference counts are not considered to be stable or well-defined values; the number of references to an object, and how that number is affected by Python code, may be different between versions.
- paket biasa¶
Традиційний package, як-от каталог, що містить файл
__init__.py
.Lihat juga namespace package.
- REPL¶
An acronym for the "read–eval–print loop", another name for the interactive interpreter shell.
- __slots__¶
Оголошення всередині класу, яке економить пам’ять шляхом попереднього оголошення місця для атрибутів екземпляра та видалення словників екземплярів. Незважаючи на те, що ця техніка популярна, її дещо складно застосувати, і її найкраще використовувати для рідкісних випадків, коли в програмі, критичній до пам’яті, є велика кількість екземплярів.
- urutan¶
An iterable which supports efficient element access using integer indices via the
__getitem__()
special method and defines a__len__()
method that returns the length of the sequence. Some built-in sequence types arelist
,str
,tuple
, andbytes
. Note thatdict
also supports__getitem__()
and__len__()
, but is considered a mapping rather than a sequence because the lookups use arbitrary hashable keys rather than integers.The
collections.abc.Sequence
abstract base class defines a much richer interface that goes beyond just__getitem__()
and__len__()
, addingcount()
,index()
,__contains__()
, and__reversed__()
. Types that implement this expanded interface can be registered explicitly usingregister()
. For more documentation on sequence methods generally, see Common Sequence Operations.- встановити розуміння¶
Компактний спосіб обробки всіх або частини елементів у ітерації та повернення набору з результатами.
results = {c for c in 'abracadabra' if c not in 'abc'}
генерує набір рядків{'r', 'd'}
. Дивіться Displays for lists, sets and dictionaries.- єдина відправка¶
Форма відправки generic function, де реалізація вибирається на основі типу одного аргументу.
- шматочок¶
Об’єкт, який зазвичай містить частину sequence. Зріз створюється з використанням нижнього індексу
[]
з двокрапками між числами, якщо вказано кілька, наприклад,variable_name[1:3:5]
. Нотація в дужках (підрядковому) використовує внутрішньо об’єктиslice
.- soft deprecated¶
A soft deprecated API should not be used in new code, but it is safe for already existing code to use it. The API remains documented and tested, but will not be enhanced further.
Soft deprecation, unlike normal deprecation, does not plan on removing the API and will not emit warnings.
- спеціальний метод¶
Метод, який неявно викликається Python для виконання певної операції над типом, наприклад додавання. Такі методи мають назви, що починаються і закінчуються подвійним підкресленням. Спеціальні методи описані в Special method names.
- standard library¶
The collection of packages, modules and extension modules distributed as a part of the official Python interpreter package. The exact membership of the collection may vary based on platform, available system libraries, or other criteria. Documentation can be found at Pustaka Standar Python.
See also
sys.stdlib_module_names
for a list of all possible standard library module names.- pernyataan¶
Оператор є частиною набору ("блоку" коду). Інструкція є або expression, або однією з кількох конструкцій із ключовим словом, таким як
if
,while
абоfor
.- static type checker¶
An external tool that reads Python code and analyzes it, looking for issues such as incorrect types. See also type hints and the
typing
module.- stdlib¶
An abbreviation of standard library.
- strong reference¶
In Python's C API, a strong reference is a reference to an object which is owned by the code holding the reference. The strong reference is taken by calling
Py_INCREF()
when the reference is created and released withPy_DECREF()
when the reference is deleted.The
Py_NewRef()
function can be used to create a strong reference to an object. Usually, thePy_DECREF()
function must be called on the strong reference before exiting the scope of the strong reference, to avoid leaking one reference.See also borrowed reference.
- t-string¶
- t-strings¶
String literals prefixed with
t
orT
are commonly called "t-strings" which is short for template string literals.- kodowanie tekstu¶
Рядок у Python — це послідовність кодових точок Unicode (у діапазоні
U+0000
--U+10FFFF
). Щоб зберегти або передати рядок, його потрібно серіалізувати як послідовність байтів.Серіалізація рядка в послідовність байтів відома як "кодування", а відтворення рядка з послідовності байтів відоме як "декодування".
Istnieje wiele różnych serializacji tekstu codecs, które są zbiorczo określane jako "kodowanie tekstu".
- berkas teks¶
Obiekt pliku może odczytywać i zapisywać obiekty
str
. Często plik tekstowy faktycznie uzyskuje dostęp do strumienia danych zorientowanego na bajty i automatycznie obsługuje kodowanie tekstu. Przykładami plików tekstowych są pliki otwierane w trybie tekstowym ('r'
lub'w'
),sys.stdin
,sys.stdout
i instancjeio.StringIO
.Дивіться також binary file щодо файлового об’єкта, здатного читати та записувати байтоподібні об’єкти.
- thread state¶
The information used by the CPython runtime to run in an OS thread. For example, this includes the current exception, if any, and the state of the bytecode interpreter.
Each thread state is bound to a single OS thread, but threads may have many thread states available. At most, one of them may be attached at once.
An attached thread state is required to call most of Python's C API, unless a function explicitly documents otherwise. The bytecode interpreter only runs under an attached thread state.
Each thread state belongs to a single interpreter, but each interpreter may have many thread states, including multiple for the same OS thread. Thread states from multiple interpreters may be bound to the same thread, but only one can be attached in that thread at any given moment.
See Thread State and the Global Interpreter Lock for more information.
- token¶
A small unit of source code, generated by the lexical analyzer (also called the tokenizer). Names, numbers, strings, operators, newlines and similar are represented by tokens.
The
tokenize
module exposes Python's lexical analyzer. Thetoken
module contains information on the various types of tokens.- teks tiga-kutip¶
Рядок, обмежений трьома лапками (") або апострофом ('). Хоча вони не надають жодної функції, недоступної для рядків із одинарними лапками, вони корисні з кількох причин. Вони дозволяють ви можете включити неекрановані одинарні та подвійні лапки в рядок, і вони можуть охоплювати кілька рядків без використання символу продовження, що робить їх особливо корисними під час написання рядків документів.
- tipe¶
The type of a Python object determines what kind of object it is; every object has a type. An object's type is accessible as its
__class__
attribute or can be retrieved withtype(obj)
.- псевдонім типу¶
Синонім типу, створений шляхом присвоєння типу ідентифікатору.
Псевдоніми типів корисні для спрощення підказок типу. Наприклад:
def remove_gray_shades( colors: list[tuple[int, int, int]]) -> list[tuple[int, int, int]]: pass
можна зробити більш читабельним таким чином:
Color = tuple[int, int, int] def remove_gray_shades(colors: list[Color]) -> list[Color]: pass
- підказка типу¶
annotation, яка визначає очікуваний тип для змінної, атрибута класу або параметра функції чи значення, що повертається.
Type hints are optional and are not enforced by Python but they are useful to static type checkers. They can also aid IDEs with code completion and refactoring.
Доступ до підказок типу глобальних змінних, атрибутів класу та функцій, але не локальних змінних, можна отримати за допомогою
typing.get_type_hints()
.- uniwersalne nowe linie¶
Спосіб інтерпретації текстових потоків, у якому все наступне розпізнається як завершення рядка: угода Unix про кінець рядка
'\n'
, угода Windows'\r\n'
, і стару конвенцію Macintosh'\r'
. Перегляньте PEP 278 і PEP 3116, а такожbytes.splitlines()
для додаткового використання.- anotasi variabel¶
annotation змінної або атрибута класу.
При анотуванні змінної або атрибута класу призначення є необов’язковим:
class C: field: 'annotation'
Анотації змінних зазвичай використовуються для підказок типу: наприклад, очікується, що ця змінна прийматиме значення
int
:count: int = 0
Синтаксис анотації змінної пояснюється в розділі Annotated assignment statements.
See function annotation, PEP 484 and PEP 526, which describe this functionality. Also see Annotations Best Practices for best practices on working with annotations.
- lingkungan virtual¶
Lingkungan runtime kooperatif yang memungkinkan pengguna dan aplikasi Python untuk menginstal dan memperbarui paket distribusi Python tanpa mengganggu perilaku aplikasi Python lain yang berjalan pada sistem yang sama.
Lihat juga
venv
.- mesin virtual¶
Комп’ютер, повністю визначений програмним забезпеченням. Віртуальна машина Python виконує bytecode, виданий компілятором байт-коду.
- walrus operator¶
A light-hearted way to refer to the assignment expression operator
:=
because it looks a bit like a walrus if you turn your head.- Дзен Python¶
Перелік принципів дизайну та філософії Python, які допоможуть зрозуміти та використовувати мову. Перелік можна знайти, ввівши "
import this
" в інтерактивному рядку.