- Single Underscore (_)
- Stores the value.
>>> 5+4
9
>>> _
9
>>> _+6
15
>>> _
15
- Ignore the value.
a,_,b=(1,2,3)
print(a,b)
>>>
1 3
lst=['ab','bc','cd']
for _,i in lst:
print(i)
>>>
b
c
d
a,*_,b=(1,2,3,4,5,6,7)
print(a,b)
>>>
1 7
- Single Pre Underscore( _variable)
It is used for internal use. When
# filename : test_1.py
def func():
print('data')
def _private_func():
print('7')
#filename : test_2.py
from test_1 import *
func()
>>>
data
_private_func()
>>>
NameError: name '_private_func' is not defined
It I import all the methods from test_1.py to test_2.py, Single Pre Underscore variable(_private_func) doesnt imported.
To avoid the error by importing the module normally as below.
#filename : test_2.py
import test_1
test_1.func()
test_1._private_func()
>>>
data
7
- Double Pre Underscore( __variable)
Name Mangling. Private access modifier. It called from within the class only. It prevents overriding variable in inherited class.
class Sample():
def __init__(self):
self.a=1
self._b=2
self.__c=3
class SecondClass(Sample):
def __init__(self):
super().__init__()
self.a='a overridden'
self._b='b overridden'
self.__c='c overridden'
obj2=SecondClass()
print(obj2.a)
print(obj2._b)
print(obj2.__c)
>>>
a overridden
b overridden
AttributeError: 'SecondClass' object has no attribute '__c'
It occurs the error because __c could not find in the herited class.
Accessible from outside with "__class__variable".
print(obj2._SecondClass__c)
>>>
c overridden
Other example below.
_SimpleClass__name='datacamp'
class SimpleClass:
def return_name(self):
return __name
obj=SimpleClass()
print(obj.return_name())
>>>
datacamp
- Double Pre Underscore and Post Underscore(__variable__)
Magic methods.
- __repr__
Represent the object.
class String:
def __init__(self, string):
self.string=string
def __repr__(self) :
return 'object:{}'.format(self.string)
if __name__=='__main__':
string1=String('hello')
print(string1)
>>>
object:hello
- __add__
Add the object.
class String:
def __init__(self, string):
self.string=string
def __repr__(self) :
return 'object:{}'.format(self.string)
def __add__(self, other):
return self.string+other
if __name__=='__main__':
string1=String('hello')
print(string1+'world')
>>>
helloworld
reference
- https://www.datacamp.com/tutorial/role-underscore-python
- https://www.geeksforgeeks.org/dunder-magic-methods-python/
'Basic Python' 카테고리의 다른 글
vars (0) | 2022.08.25 |
---|---|
__new__, __init__ (0) | 2022.07.13 |
instancemethod, classmethod, staticmethod (0) | 2022.07.01 |
TypeError : Can't instantiate abstract class with abstract method (0) | 2022.06.29 |
title, items (0) | 2022.06.29 |