[Python] Role of Underscore(_)

ss9909·2022년 8월 20일
0

Python

목록 보기
1/1
post-thumbnail

파이썬을 사용하다 보면 underscore를 만나게 된다.
어떤 경우에 사용하는지 사례를 정리하고자 기록을 남긴다.

Underscore Use Cases

1. 인터프리터에서 사용

>>> 1+2
2
>>> _
3

2. Value를 무시할 때 사용

# ignoring a value
>>> x, _, z = (1, 2, 3)
>>> _
2
# ignoring multiple values
# *(variable) used to assign multiple value to a variable 
# as list while unpacking
# it's called "Extended Unpacking"
>>> x,*_,z =(1,2,3,4,5,6,7,8,9,10)
>>> x
1
>>> _
[2, 3, 4, 5, 6, 7, 8, 9]
>>> z
10

3. 자릿수를 분리할 때 사용

# different number systems
# you can also check whether they are correct or not 
#  by coverting them into integer using "int" method
million = 1_000_000 # 1000000
binary = 0b_0010    # 0b010
octa = 0o_64   		# 0o64
hexa = 0x_23_ab		# 0x23ab

4. 변수 네이밍시 사용

다음과 같이 4가지 경우가 존재한다.
1. Single Pre Underscore: _variable
2. Signle Post Underscore: variable_
3. Double Pre Underscores: __variable
4. Double Pre and Post Underscores: __variable__

4.1 변수 앞에 한 개의 언더스코어

Single Pre Underscore is used for internal use. (weak internal use indicator)
일반적인 이름의 변수는 여러개가 있을 수 있다. 변수이름이 num이라면 많은 변수가 같은 이름을 갖고 있을 것이다. 그런 경우에 내부에서 사용하기 위한 네이밍 컨벤션

class Test:

    def __init__(self):
        self.name = "datacamp"
        self._num = 7

obj = Test()
print(obj.name)
print(obj._num)

4.2 변수 뒤에 한개의 언더스코어

Sometimes if you want to use Python Keywords as a variable, function or class names, you can use this convention for that.
"Python keysords"를 변수, 함수 또는 클래스 이름으로 사용하고 싶을 때 사용하는 네이밍 컨벤션
언더스코어를 붙임으로써 파이썬 키워드와의 중복을 피해 사용할 수 있다.

>>> def function(class):
  File "<stdin>", line 1
    def function(class):
                 ^
SyntaxError: invalid syntax


>>> def function(class_):
...     pass
...

profile
이름 짓는 게 어려운 사람

0개의 댓글