Double underscores in python

5 способов использования подчеркивания (_) в Python

Обложка: 5 способов использования подчеркивания (_) в Python

Подчеркиванию (_) в Python отводится особенное место. Если в большинстве других языков оно используется в названиях переменных и функций, то в Python подчеркивание (_) обладает гораздо большей властью. Например, если вы программировали на Python, то вам должен быть знаком следующий синтаксис: for _ in range(10) или __init__(self) .

В этой статье мы рассмотрим 5 способов использования (_) в Python:

  1. Хранение значения последнего выражения в интерпретаторе.
  2. Игнорирование некоторых значений.
  3. Задание специальных значений переменным или функциям.
  4. Использование функций «Internationalization(i18n)» и «Localization(l10n)».
  5. Отделение цифр числа друг от друга.

Пройдемся по каждому случаю отдельно.

Хранение значения последнего выражения в интерпретаторе

Интерпретатор Python хранит значение последнего выражения в специальной переменной «_». Эта возможность сначала использовалась в стандартном CPython-интерпретаторе, но теперь она доступна и в других интерпретаторах.

>>> 10 10 >>> _ 10 >>> _ * 3 30 >>> _ * 20 600

Игнорирование некоторых значений

Подчеркивание (_) также используется для игнорирования ненужных вам значений.

# Ignore a value when unpacking x, _, y = (1, 2, 3) # x = 1, y = 3 # Ignore the multiple values. It is called "Extended Unpacking" which is available in only Python 3.x x, *_, y = (1, 2, 3, 4, 5) # x = 1, y = 5 # Ignore the index for _ in range(10): do_something() # Ignore a value of specific location for _, val in list_of_tuple: do_something()

Задание специальных значений для имен переменных или функций

PEP8, руководство по написанию кода на Python, выделяет 4 способа задания имен.

_single_leading_underscore

Таким способом задаются частные переменные, функции, методы и классы в модуле. Все, что использует такой способ задания имени, будет проигнорировано в from module import * .

_internal_name = 'one_nodule' # private variable _internal_version = '1.0' # private variable class _Base: # private class _hidden_factor = 2 # private variable def __init__(self, price): self._price = price def _double_price(self): # private method return self._price * self._hidden_factor def get_double_price(self): return self._double_price()

single_trailing_underscore_

Такой метод задания имен используется для избежания конфликтов со встроенными именами или классами.

Tkinter.Toplevel(master, class_='ClassName') # Avoid conflict with 'class' keyword list_ = List.objects.get(1) # Avoid conflict with 'list' built-in type

__double_leading_underscore

Двойное подчеркивание (__) используется для искажения имен атрибутов в классе. Если мы создадим метод с именем «__method» в классе с именем «ClassName», то вызвать этот метод так: «ClassName.__method» — у нас уже не получится. Для дополнительной информации вы можете прочитать о способах задания имен в Python.

class A: def _single_method(self): pass def __double_method(self): # for mangling pass class B(A): def __double_method(self): # for mangling pass

__double_leading_and_trailing_underscore__

Такой способ именования используется для специальных переменных или функций, таких как __init__ или __len__ .

class A: def __init__(self, a): # use special method '__init__' for initializing self.a = a def __custom__(self): # custom special method. you might almost do not use it pass

Использование функций «Internationalization(i18n)» и «Localization(l10n)»

# see official docs : https://docs.python.org/3/library/gettext.html import gettext gettext.bindtextdomain('myapplication','/path/to/my/language/directory') gettext.textdomain('myapplication') _ = gettext.gettext # . print(_('This is a translatable string.'))

Отделение цифр числа друг от друга

Эта возможность была добавлена в Python 3.6. Она позволяет существенно облегчить восприятие и написание больших чисел.

dec_base = 1_000_000 bin_base = 0b_1111_0000 hex_base = 0x_1234_abcd print(dec_base) # 1000000 print(bin_base) # 240 print(hex_base) # 305441741

Источник

Читайте также:  Применение абзацев

What is the Meaning of Double Underscore in Python

Python Certification Course: Master the essentials

Python interpreter uses the double underscore to avoid naming conflict in Python subclasses. It uses the double underscore to rewrite the attribute name in Python classes.

The rewriting of the attribute name in order to avoid collision is called name mangling .

Double Underscore as Prefix in Python

The syntax for double underscore as a prefix in Python is as :

The double underscore tells the Python interpreter to rewrite the attribute names in the Python class to avoid any naming collision when the Python class is inherited.

Let’s take an example to understand the use of double underscore as a prefix in Python.

DOUBLE UNDERSCORE AS PREFIX

Explanation:

In the above code, the DemoClass uses the variables var1,var2, and var3 to store values. These values can be modified depending on the condition passed in the program.

The dir(obj1) commands gives all the list of valid attributes in the class whose object is passed in the dir() function.

As in the above output, we can see that var1 and _var2 variable names are identical in the output but the variable __var3 is changed to _DemoClass__var3 . This name tangling is done to protect the variable from getting overridden when the DemoClass is inherited i.e in the subclasses.

Leading and Trailing Double Underscore

The syntax for leading and trailing double underscores in Python is as :

The process of rewriting the attribute name doesn’t takes place i.e name mangling does not occur when leading and trailing underscore are applied around a variable.

Let’s take an example to understand the use of leading and trailing underscores.

Читайте также:  Python install python developer

Explanation:

In the above code, the Python interpreter ignores the trailing and leading underscore before and after variable var1. So, name mangling does not occur in the case of leading and trailing underscores. The Demo(). var1 returns the actual value stored in the var1 variable i.e the output is 12 .

Some unique names in Python like init and call with leading and trailing underscores are reserved in Python for a particular use.

Examples of Double Underscore in Python

Let’s take an example of a Double underscore in Python to understand its use.

OUTPUT OF DOUBLE UNDERSCORE

Explanation:

In the above code, the ExampleClass uses the variables var1, baz, and foo to store values. These values can be modified depending on the condition passed in the program.

The dir(exampleObj) commands gives all the list of valid attributes in the class whose object is passed in the dir() function.

As in the above output, we can see that var1 and _baz variable names are same in the output but the variable __foo is changed to _ExampleClass__foo . This name tangling is done to protect the variable from getting overridden when the ExampleClass is inherited i.e in the subclasses.

Conclusion

  • Double underscore prefix is used in Python to avoid naming conflict.
  • Rewriting attribute names to avoid naming collision is called name mangling .
  • Leading and trailing double underscore does not rewrite the attribute name.
  • Name mangling does not occur in the case of leading and trailing double underscore.

Источник

Double Underscore in Python

Double Underscore in Python

  1. Use the Double-Leading Underscore in Python
  2. Use Double Leading and Trailing Underscore in Python

Both the underscore ( _ ) and the double underscore ( __ ) hold great significance in the world of Python programming and are excessively used by programmers for different purposes. Double underscores are pretty handy and are frequently encountered in Python code.

In this article, we will discuss the meaning of the double underscore in Python.

Use the Double-Leading Underscore in Python

When the double underscore leads a given identifier ( __var ), the name mangling process occurs on that particular identifier.

Name mangling, in simple terms, is to basically rewrite the attribute name in order to prevent naming conflicts with the subclasses.

Читайте также:  Server php http hostname

You can use the following code to explain the double leading underscore in Python.

class E1:  def __init__(self):  self.bar = 11  self._baz = 23  self.__foo = 23 x = E1() print(dir(x)) 
['_E1__foo', '__doc__', '__init__', '__module__', '_baz', 'bar'] 

Explanation

  • In the code above, we take a class and compare the single underscore, double underscore, and normal elements.
  • The elements foo , bar , baz are simple keywords used as a placeholder here for the values that happen to change on conditions passed to the program or new information received by the program.
  • The dir() function is used here to provide a list of valid attributes of the given object passed as an argument in the function.

In the code above, we notice that the bar and _baz variable looks to be unchanged, while the __foo variable has been changed to _E1__foo . This is the process of name tangling occurring on the variable, and it is done to safeguard the variable against getting overridden in subclasses.

This process of name mangling of the variables with leading double underscore is totally transparent to the programmer. Name mangling interacts with and changes everything that leads with a double underscore, including functions.

Use Double Leading and Trailing Underscore in Python

When a variable is surrounded by double underscore on both the leading and trailing sides, the process of name mangling is not applied to it.

Variables clustered by the double underscore as both the prefix and the postfix are ignored by the Python interpreter.

You can use the following code to explain the double leading and trailing underscore in Python.

class A:  def __init__(self):  self.__foo__ = 10  print(A().__foo__) 

In the code above, the foo variable with a double underscore as prefix and postfix is ignored by the interpreter, and the name mangling does not occur. The value of this function is returned as the output, which proves that the variable exists in the object attribute list.

Some unique names, like init or call that contains both the leading and the trailing double underscore, are reserved in the Python language for special use.

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

Related Article — Python Syntax

Источник

Оцените статью