Соглашения об именах с подчеркиванием в Python
подчеркивание _ является особенным в Python. В то время как подчеркивание используется только для переменных и функций типа «змея» на многих языках, но в Python он имеет особое значение. Они широко используются в различных сценариях, включая случаи, когда мы хотим игнорировать какое-либо значение, или при объявлении переменных, методов и т. Д.
Одиночные и двойные подчеркивания имеют значение в именах переменных и методов Python. Часть смысла просто условна, в то время как часть его реализуется интерпретатором Python.
В этой статье мы обсудим пять шаблонов подчеркивания и соглашения об именах, а также то, как они влияют на поведение наших программ Python. Понимание этих концепций очень поможет, особенно при написании сложного кода.
К концу этого поста у нас будет четкое представление о том, как и где использовать какой шаблон подчеркивания в нашем соглашении об именах. Итак, приступим.
1. Подчеркивание одной лидирующей позиции: _var
Префикс подчеркивания предназначен для подсказки другому программисту, что переменная или метод, начинающиеся с одного символа подчеркивания, предназначены для внутреннего использования. Это соглашение определено в PEP 8.
Имя с префиксом подчеркивания (например, _spam ) должно рассматриваться как закрытая часть API (будь то функция, метод или элемент данных). Это следует рассматривать как деталь реализации и может быть изменено без предварительного уведомления.
Взгляните на следующий пример:
Давайте создадим экземпляр вышеуказанного класса и попытаемся получить доступ к атрибутам name и _age .
Таким образом, одинарный префикс подчеркивания в Python — это просто согласованное соглашение и не накладывает никаких ограничений на доступ к значению этой переменной.
2. Двойной лидирующий знак подчеркивания: __var
Использование двойного подчеркивания ( __ ) перед именем (в частности, именем метода) не является соглашением; для интерпретатора это имеет особое значение.
Python искажает эти имена и используется, чтобы избежать конфликтов имен с именами, определенными подклассами.
Это также называется изменением имени — интерпретатор изменяет имя переменной таким образом, что затрудняет создание коллизий при дальнейшем расширении класса.
Чтобы лучше понять, мы создадим наш игрушечный класс для экспериментов:
Давайте посмотрим на атрибуты его объекта с помощью встроенной dir() функции:
Из приведенного выше списка атрибутов объекта мы видим, что self.name и self._age не изменились и ведут себя одинаково.
Однако __id искажен до _Person__id . Это изменение имени, которое применяет интерпретатор Python. Это делается для защиты переменной от переопределения в подклассах.
Теперь, если мы создадим подкласс Person , скажем Employee , мы не сможем легко переопределить переменную Person __id .
Предполагаемое поведение здесь почти эквивалентно переменным final в Java и не виртуальным в C ++.
3. Одиночное подчеркивание в конце: var_
Соглашение об именах с одним завершающим подчеркиванием используется во избежание конфликтов с ключевыми словами Python.
Когда наиболее подходящее имя для переменной уже занято ключевым словом, добавляется единственное соглашение о подчеркивании, чтобы разрешить конфликт имен. Типичный пример включает использование class или других ключевых слов в качестве переменных.
4. Двойное начальное и конечное подчеркивание: __var__
Имена с двойным подчеркиванием в начале и в конце («dunders») зарезервированы для особого использования, например, метод the __init__ для конструкторов объектов или метод __call__ для создания вызываемых объектов. Эти методы известны как методы dunder.
Насколько мне известно, это просто соглашение, способ для системы Python использовать имена, которые не будут конфликтовать с именами, определяемыми пользователем. Следовательно, d unders — это всего лишь соглашение, и интерпретатор Python не затрагивает их.
dunders достигают желаемой цели — делают определенные методы особенными, а также делают их такими же, как и другие простые методы, во всех аспектах, кроме соглашения об именах.
Честно говоря, ничто не мешает нам написать собственное dunder имя, но лучше не использовать их в наших программах, чтобы избежать конфликтов с будущими изменениями в языке Python. (Обратитесь к моей истории, которая подробно описывает dunders).
5. Одинарное подчеркивание: _
Согласно соглашению, в качестве имени иногда используется отдельный символ подчеркивания, чтобы указать, что переменная является временной или незначительной.
Например, в следующем цикле нам не нужен доступ к работающему индексу, и мы можем использовать « _ », чтобы указать, что это всего лишь временное значение:
Опять же, это означает только «по соглашению», и в интерпретаторе Python не запускается какое-либо особое поведение. Одиночное подчеркивание — это просто допустимое имя переменной, которое иногда используется для этой цели.
Выводы:
Знание различных шаблонов подчеркивания поможет в написании нашего кода более Pythonic.
Вот краткое изложение наших 5 шаблонов подчеркивания для соглашений об именах, которые мы рассмотрели выше.
2. Lexical analysis¶
A Python program is read by a parser. Input to the parser is a stream of tokens, generated by the lexical analyzer. This chapter describes how the lexical analyzer breaks a file into tokens.
Python reads program text as Unicode code points; the encoding of a source file can be given by an encoding declaration and defaults to UTF-8, see PEP 3120 for details. If the source file cannot be decoded, a SyntaxError is raised.
2.1. Line structure¶
A Python program is divided into a number of logical lines.
2.1.1. Logical lines¶
The end of a logical line is represented by the token NEWLINE. Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax (e.g., between statements in compound statements). A logical line is constructed from one or more physical lines by following the explicit or implicit line joining rules.
2.1.2. Physical lines¶
A physical line is a sequence of characters terminated by an end-of-line sequence. In source files and strings, any of the standard platform line termination sequences can be used — the Unix form using ASCII LF (linefeed), the Windows form using the ASCII sequence CR LF (return followed by linefeed), or the old Macintosh form using the ASCII CR (return) character. All of these forms can be used equally, regardless of platform. The end of input also serves as an implicit terminator for the final physical line.
When embedding Python, source code strings should be passed to Python APIs using the standard C conventions for newline characters (the \n character, representing ASCII LF, is the line terminator).
2.1.3. Comments¶
A comment starts with a hash character ( # ) that is not part of a string literal, and ends at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Comments are ignored by the syntax.
2.1.4. Encoding declarations¶
If a comment in the first or second line of the Python script matches the regular expression coding[=:]\s*([-\w.]+) , this comment is processed as an encoding declaration; the first group of this expression names the encoding of the source code file. The encoding declaration must appear on a line of its own. If it is the second line, the first line must also be a comment-only line. The recommended forms of an encoding expression are
which is recognized also by GNU Emacs, and
which is recognized by Bram Moolenaar’s VIM.
If no encoding declaration is found, the default encoding is UTF-8. In addition, if the first bytes of the file are the UTF-8 byte-order mark ( b’\xef\xbb\xbf’ ), the declared file encoding is UTF-8 (this is supported, among others, by Microsoft’s notepad).
If an encoding is declared, the encoding name must be recognized by Python (see Standard Encodings ). The encoding is used for all lexical analysis, including string literals, comments and identifiers.
2.1.5. Explicit line joining¶
Two or more physical lines may be joined into logical lines using backslash characters ( \ ), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:
A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.
2.1.6. Implicit line joining¶
Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes. For example:
Implicitly continued lines can carry comments. The indentation of the continuation lines is not important. Blank continuation lines are allowed. There is no NEWLINE token between implicit continuation lines. Implicitly continued lines can also occur within triple-quoted strings (see below); in that case they cannot carry comments.
2.1.7. Blank lines¶
A logical line that contains only spaces, tabs, formfeeds and possibly a comment, is ignored (i.e., no NEWLINE token is generated). During interactive input of statements, handling of a blank line may differ depending on the implementation of the read-eval-print loop. In the standard interactive interpreter, an entirely blank logical line (i.e. one containing not even whitespace or a comment) terminates a multi-line statement.
2.1.8. Indentation¶
Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.
Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.
Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.
Cross-platform compatibility note: because of the nature of text editors on non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the indentation in a single source file. It should also be noted that different platforms may explicitly limit the maximum indentation level.
A formfeed character may be present at the start of the line; it will be ignored for the indentation calculations above. Formfeed characters occurring elsewhere in the leading whitespace have an undefined effect (for instance, they may reset the space count to zero).
The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using a stack, as follows.
Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. If it is smaller, it must be one of the numbers occurring on the stack; all numbers on the stack that are larger are popped off, and for each number popped off a DEDENT token is generated. At the end of the file, a DEDENT token is generated for each number remaining on the stack that is larger than zero.
Here is an example of a correctly (though confusingly) indented piece of Python code:
The following example shows various indentation errors:
(Actually, the first three errors are detected by the parser; only the last error is found by the lexical analyzer — the indentation of return r does not match a level popped off the stack.)
2.1.9. Whitespace between tokens¶
Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens. Whitespace is needed between two tokens only if their concatenation could otherwise be interpreted as a different token (e.g., ab is one token, but a b is two tokens).
2.2. Other tokens¶
Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist: identifiers, keywords, literals, operators, and delimiters. Whitespace characters (other than line terminators, discussed earlier) are not tokens, but serve to delimit tokens. Where ambiguity exists, a token comprises the longest possible string that forms a legal token, when read from left to right.
2.3. Identifiers and keywords¶
Identifiers (also referred to as names) are described by the following lexical definitions.
The syntax of identifiers in Python is based on the Unicode standard annex UAX-31, with elaboration and changes as defined below; see also PEP 3131 for further details.
Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase letters A through Z , the underscore _ and, except for the first character, the digits 0 through 9 .
Python 3.0 introduces additional characters from outside the ASCII range (see PEP 3131). For these characters, the classification uses the version of the Unicode Character Database as included in the unicodedata module.
Identifiers are unlimited in length. Case is significant.
The Unicode category codes mentioned above stand for:
Lu — uppercase letters
Ll — lowercase letters
Lt — titlecase letters
Lm — modifier letters
Lo — other letters
Nl — letter numbers
Mn — nonspacing marks
Mc — spacing combining marks
Nd — decimal numbers
Pc — connector punctuations
Other_ID_Start — explicit list of characters in PropList.txt to support backwards compatibility
All identifiers are converted into the normal form NFKC while parsing; comparison of identifiers is based on NFKC.
A non-normative HTML file listing all valid identifier characters for Unicode 14.0.0 can be found at https://www.unicode.org/Public/14.0.0/ucd/DerivedCoreProperties.txt
2.3.1. Keywords¶
The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:
2.3.2. Soft Keywords¶
New in version 3.10.
Some identifiers are only reserved under specific contexts. These are known as soft keywords. The identifiers match , case and _ can syntactically act as keywords in contexts related to the pattern matching statement, but this distinction is done at the parser level, not when tokenizing.
As soft keywords, their use with pattern matching is possible while still preserving compatibility with existing code that uses match , case and _ as identifier names.
2.3.3. Reserved classes of identifiers¶
Certain classes of identifiers (besides keywords) have special meanings. These classes are identified by the patterns of leading and trailing underscore characters:
Not imported by from module import * .
In a case pattern within a match statement, _ is a soft keyword that denotes a wildcard .
Separately, the interactive interpreter makes the result of the last evaluation available in the variable _ . (It is stored in the builtins module, alongside built-in functions like print .)
Elsewhere, _ is a regular identifier. It is often used to name “special” items, but it is not special to Python itself.
The name _ is often used in conjunction with internationalization; refer to the documentation for the gettext module for more information on this convention.
It is also commonly used for unused variables.
System-defined names, informally known as “dunder” names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.
Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes. See section Identifiers (Names) .
2.4. Literals¶
Literals are notations for constant values of some built-in types.
2.4.1. String and Bytes literals¶
String literals are described by the following lexical definitions:
One syntactic restriction not indicated by these productions is that whitespace is not allowed between the stringprefix or bytesprefix and the rest of the literal. The source character set is defined by the encoding declaration; it is UTF-8 if no encoding declaration is given in the source file; see section Encoding declarations .
In plain English: Both types of literals can be enclosed in matching single quotes ( ‘ ) or double quotes ( " ). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash ( \ ) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.
Bytes literals are always prefixed with ‘b’ or ‘B’ ; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.
Both string and bytes literals may optionally be prefixed with a letter ‘r’ or ‘R’ ; such strings are called raw strings and treat backslashes as literal characters. As a result, in string literals, ‘\U’ and ‘\u’ escapes in raw strings are not treated specially. Given that Python 2.x’s raw unicode literals behave differently than Python 3.x’s the ‘ur’ syntax is not supported.
New in version 3.3: The ‘rb’ prefix of raw bytes literals has been added as a synonym of ‘br’ .
New in version 3.3: Support for the unicode legacy literal ( u’value’ ) was reintroduced to simplify the maintenance of dual Python 2.x and 3.x codebases. See PEP 414 for more information.
A string literal with ‘f’ or ‘F’ in its prefix is a formatted string literal; see Formatted string literals . The ‘f’ may be combined with ‘r’ , but not with ‘b’ or ‘u’ , therefore raw formatted strings are possible, but formatted bytes literals are not.
In triple-quoted literals, unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the literal. (A “quote” is the character used to open the literal, i.e. either ‘ or " .)
Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are:
Русские Блоги
Подчеркивания, которые должны понимать начинающие Python

Нижнее подчеркивание ( _ ) Имеет особую роль в языке Python.
В большинстве языков программирования подчеркивание — это дефис при именовании переменной или функции, но в языке Python это нечто большее. Если вы программист на Python, например _ in range(10) , __init__(self) Подобные проблемы должны быть вам знакомы.
В этой статье подробно описывается подчеркивание ( _ ) Чтобы помочь новичкам понять это.
В языке Python подчеркивания в основном используются в следующих 5 областях:
- В интерактивном режиме сохраните значение самого последнего выражения
- Игнорировать значение («Я не важен»)
- Придать особое значение именам переменных или функций
- Названо как функция интернационализации или локализации
- Используется как разделитель в числовых значениях
Примечание. Независимо от того, работаете ли вы на Python или занимаетесь хобби, помните: опыт разработки проекта всегда является основным. Если у вас нет упражнений для нового проекта или у вас нет учебного курса Python, вы можете перейти к Редактор связи Python.Юбка: Qiyiyi 9qiqiba и 5 (гомофония числа) можно найти в разделе преобразования.В нем много новых учебных проектов по питону, и вы также можете обмениваться идеями со старыми драйверами!
Объясняется одно за другим ниже.
Используется в интерактивном режиме
В интерактивном режиме Python, если вы вызываете _ , Отобразит значение самого последнего выражения. Эта функция доступна в стандартном интерактивном режиме, и вы также можете использовать ее в других интерактивных парсерах Python.
Означает игнорирование значения
Подчеркивание также может использоваться, чтобы указать, что значение следует игнорировать. Если вам не нужно значение или значение бесполезно, вы можете использовать подчеркивание в качестве соответствующей переменной.
Придать особое значение именам переменных или функций
Чаще всего символы подчеркивания используются в именах. PEP8 — это соглашение, разработанное Python, которое согласовывает метод именования в 4.
Начало одиночного подчеркивания
Имена переменных, функций, методов и классов, начинающиеся с одного символа подчеркивания, предназначены для объявления объекта закрытым. Согласно этой оговорке, используйте from module import * Соответствующий объект не может быть импортирован.
Однако Python не поддерживает реальную приватизацию, поэтому мы не можем принудительно приватизировать объект, и его можно вызывать напрямую из других модулей. Иногда мы говорим, что такие приватизированные объекты являются «слабыми индикаторами для внутреннего использования».
Окончание с одним подчеркиванием
Во избежание конфликтов с ключевыми словами Python и другими встроенными именами объектов этот метод именования часто используется, и вы не можете его использовать.
Начните с двойного подчеркивания
Это грамматика, выходящая за рамки общих условностей. Когда программа запущена, синтаксический анализатор Python переименует имена атрибутов и методов в классах, которые начинаются с двойного подчеркивания, чтобы избежать конфликтов между одинаковыми именами в разных классах. Основное правило состоит в том, чтобы имена начинались с двойного подчеркивания перед именами. префикс типа "_ClassName" стиль.
Например, в классе есть имя __method Метод, это название будет переименовано _ClassName__method форма.
Как упоминалось выше, мы не можем использовать свойства и методы, начинающиеся с двойного подчеркивания. ClassName.__method Поэтому некоторые люди расценивают это как настоящую приватизацию, однако этот метод приватизации здесь не рекомендуется из-за правил именования Python.
Примечание переводчика: мнения автора приводятся здесь только для справки. _namne Таким образом, приватизация — это согласованная приватизация, а не настоящая приватизация; __name Этот метод действительно ведет к «приватизации», но есть разные мнения о том, принят ли он в программировании. Другими словами, в Python есть разные понимания «приватизации».
Двойное подчеркивание начало и конец
Это соглашение используется для специальных переменных или методов, называемых «магическими методами» (переводчик думает: «магический метод», что лучше перевести в «магический метод»? Эти специальные методы заставляют учащихся чувствовать себя очень «волшебными».), Например в виде __init__ , __len__ . Эти методы предоставляют некоторые специальные функции, такие как __file__ Объявить локальный файл Python, __eq__ Реализованное выражение a == b 。
Средний разработчик редко определяет эти методы, но при определении класса __init__ Это часто выполняется во время создания экземпляра.
Названо функцией интернационализации или локализации
Это просто соглашение, а не синтаксис функции. Следовательно, подчеркивание не означает интернационализацию (i18n) или локализацию (l10n) только потому, что эта привычка происходит от привычки языка C.
Модуль gettext встроенной стандартной библиотеки можно использовать для демонстрации i18n / l10n. Фреймворк веб-разработки Django на Python также поддерживает i18n / l10n и применяет это соглашение.
Разделитель между числами
Эта функция была добавлена в Python 3.6 с использованием подчеркивания в качестве разделителя чисел.
в заключении
В этой статье кратко описывается использование понижающей замены в Python. Некоторые методы могут быть для вас новыми, например i18n / l10n, о которых я раньше не знал. Также обратите внимание: работаете ли вы на Python или занимаетесь хобби, помните: опыт разработки проекта всегда является основным.Если вам не хватает практики нового проекта или у вас нет подробного руководства по Python, вы можете перейти на сайт обмена Python редактора. Skirt: Qiyiyi Вы можете найти его под преобразованием 9,7-семи-черт и 5 (гомофония чисел) .В нем много новых учебных проектов по питону, и вы также можете обмениваться идеями со старыми драйверами!
Текст и изображения в этой статье взяты из Интернета и их собственные идеи. Они предназначены только для обучения и общения и не имеют коммерческого использования. Авторские права принадлежат первоначальному автору. Если у вас есть какие-либо вопросы, пожалуйста, свяжитесь с нами вовремя для обработки.
Ключевые слова и идентификаторы в Python
Ключевые слова — это зарезервированные слова, используемые в Python, которые имеют особое значение для компилятора. Ключевые слова нельзя использовать в качестве имен переменных, функций или любых других идентификаторов. Они используются для определения синтаксиса и структуры языка Python. Все ключевые слова, кроме True , False и None , пишутся строчными буквами (нижний регистр).
Список всех ключевых слов в Python:
| Ключевые слова Python | ||||
| False | await | else | import | pass |
| None | break | except | in | raise |
| True | class | finally | is | return |
| and | continue | for | lambda | try |
| as | def | from | nonlocal | while |
| assert | del | global | not | with |
| async | elif | if | or | yield |
Идентификаторы Python
Идентификаторы — это имена переменных, классов, методов и т.д. Например:
Здесь language — это переменная (идентификатор), которая содержит значение ‘Python’ .
Мы не можем использовать ключевые слова в качестве имен переменных, поскольку это зарезервированные слова, встроенные в Python. Например:
Данный код приведет к ошибке, потому что continue является ключевым словом, которое нельзя использовать в качестве имени переменной.
Правила именования идентификаторов
Ключевые слова не могут быть идентификаторами.
Идентификаторы чувствительны к регистру.
Идентификаторы могут состоять из букв и цифр. Однако идентификатор должен начинаться либо с буквы, либо с _ (нижнее подчеркивание). Идентификатор не может начинаться с цифры.
Принято начинать идентификатор с буквы, а не с _ .
Пробелы не допускаются.
Нельзя использовать специальные символы, такие как ! , @ , # , $ и др.
Примеры допустимых и недопустимых идентификаторов в Python:
| Допустимые идентификаторы | Недопустимые идентификаторы |
| value | @value |
| return_day | return |
| highest_price | highest price |
| name2 | 2name |
| convert_to_int | convert to_int |
То, что нужно запомнить
Python — это язык, чувствительный к регистру (например, Variable и variable — это не одно и то же).
Всегда используйте в качестве идентификаторов имена, которые имеют смысл. Хотя c = 10 является допустимым, запись count = 10 имеет больше смысла, и гораздо легче понять, что она представляет.
Слова можно разделять с помощью нижнего подчеркивания, например, this_is_still_a_variable .