|
| 1 | +The underscore (_) has special meaning in Python. |
| 2 | + |
| 3 | +### For ignoring values: |
| 4 | + |
| 5 | +If you do not need a specific value(s) while unpacking an object, just assign the value(s) to an underscore. |
| 6 | + |
| 7 | +``` |
| 8 | +x, _, y = (1, 2, 3) |
| 9 | +
|
| 10 | +# Ignore the multiple values. It is called "Extended Unpacking" which is available in only Python 3.x |
| 11 | +x, *_, y = (1, 2, 3, 4, 5) # x = 1, y = 5 |
| 12 | +
|
| 13 | +# ignore the index |
| 14 | +for _ in range(10): |
| 15 | + task() |
| 16 | +
|
| 17 | +# Ignore a value of specific location |
| 18 | +for _, val in list_of_tuples: # [(1,2),(3,4),(5,6)] |
| 19 | + print(val) # output - 3 |
| 20 | +``` |
| 21 | + |
| 22 | +### _single_leading_underscore |
| 23 | + |
| 24 | +This convention is used for declaring private variables, functions, methods and classes. Anything with this convention are ignored in `from module import *`. |
| 25 | + |
| 26 | +### single_trailing_underscore_ |
| 27 | + |
| 28 | +This convention should be used for avoiding conflict with Python keywords or built-ins. |
| 29 | + |
| 30 | +``` |
| 31 | +class_ = dict(n=50, boys=25, girls=25) |
| 32 | +# avoiding clash with the class keyword |
| 33 | +``` |
| 34 | + |
| 35 | +### __double_leading_underscore |
| 36 | + |
| 37 | +Double underscore will mangle the attribute names of a class to avoid conflicts of attribute names between classes. Python will automatically add "\_ClassName" to the front of the attribute name which has a double underscore in front of it. |
| 38 | + |
| 39 | +[Read more](https://docs.python.org/3/tutorial/classes.html#private-variables) |
| 40 | + |
| 41 | +### __double_leading_and_trailing_underscore\_\_ |
| 42 | + |
| 43 | +This convention is used for special variables or ( magic )methods such as__init_\_, __len\__. These methods provides special syntactic features. |
| 44 | + |
| 45 | +``` |
| 46 | +class FileObject: |
| 47 | + '''Wrapper for file objects to make sure the file gets closed on deletion.''' |
| 48 | +
|
| 49 | + def __init__(self, filepath='~', filename='sample.txt'): |
| 50 | + # open a file filename in filepath in read and write mode |
| 51 | + self.file = open(join(filepath, filename), 'r+') |
| 52 | +``` |
| 53 | + |
| 54 | +[List of magic methods](https://github.com/RafeKettler/magicmethods/blob/master/magicmethods.pdf). |
| 55 | + |
0 commit comments