728x90
2021-04-02 수정 dunder method 예제 추가*
이 글은 슬기로운 파이썬 트릭의 내용에 기반해 작성한 글입니다.
2.4 밑줄 문자와 던더
- 파이썬에서 변수명에 밑줄을 추가하는 경우가 있는데 각각은 의미를 가진다.
_var
- 변수 앞에 하나의 _를 붙이는건 method 내부에서만 쓰일 것이라는 의도를 알리는 목적
- 이 방식으로는 해당 변수에 접근하는 것을 방해하지는 않음
- 그러나
from module import *
와 같은 와일드 카드 임포트방식으로 모듈을 불러오는 경우에 _가 앞에 붙은 것은 모두 가져오지 않음
var_
- 이 경우에는 python에서 변수로 사용할 수 없는 이름으로 선언하고 싶은 경우에 사용
- 예를 들면, class나 int는 파이썬의 키워드로 사용하고 있기 때문에 사용할 수 없지만 사용하고자 할 때 class나 int와 같이 선언해 충돌을 방지
- 이 방법도 관례적인 방법으로 프로그램에 다른 영향을 주지 않음
__var
- 변수 앞에 _를 두개 붙이면 실수로 수정되지 않도록 name mangling이라고 하는 과정이 진행됨
- name mangling이란 클래스 내에서 변수명이 바뀌는 것을 의미한다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Test: | |
def __init__self: | |
self.var = 1 | |
self._var = 2 | |
self.__var = 3 | |
t = Test | |
dirt | |
---- | |
['_Test__var', # <<< name mangling | |
'__class__', | |
'__delattr__', | |
'__dict__', | |
'__dir__', | |
'__doc__', | |
'__eq__', | |
'__format__', | |
'__ge__', | |
'__getattribute__', | |
'__gt__', | |
'__hash__', | |
'__init__', | |
'__init_subclass__', | |
'__le__', | |
'__lt__', | |
'__module__', | |
'__ne__', | |
'__new__', | |
'__reduce__', | |
'__reduce_ex__', | |
'__repr__', | |
'__setattr__', | |
'__sizeof__', | |
'__str__', | |
'__subclasshook__', | |
'__weakref__', | |
'_var', | |
'var'] |
- __var는 실수로 수정되는 것을 막기위해 name mangling을 수행할 변수에 해당함
- 변수 뿐만 아니라 method에도 적용이 됨
__var__
- 앞과 뒤에 모두 __가 붙으면 던더 메소드라고 함
- 던더는 double underscore를 줄여 부르는 말
- var는 파이썬에서 특수용도로 예약이 되어있고, 버전이 바뀌면서 수정될 수 있기 때문에, 충돌을 막기 위해 이런 방식을 쓰지 않는 것이 좋음
- 아래의 예에서 class내에
__add__
method는 dundeer_example 클래스로 + 연산을 하게되면__add__
가 호출됨
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class dunder_example: | |
def __init__self,x: | |
self.x = x | |
def __add__self,other: | |
return dunder_exampleself.x+other.x∗0.5 | |
a = dunder_example5 # a.x = 5 | |
b = dunder_example10 # b.x = 10 | |
c = a+b # a.x + b.x*0.5 | |
d = b+a # b.x + a.x*0.5 | |
printc.x | |
printd.x | |
>>> 10.0 | |
>>> 12.5 |
- python의 dunder method를 잘 정리한 블로그1를 참고
_ underscore
- 관례로 변수가 임시적이거나 중요하지 않음을 나타냄
- 반복문에서 인덱스에 접근할 필요가 없을 때 임시적인 값임을 표현하기 위해
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
for _ in range32: | |
print′Temp!′ |
- 여러 output을 반환하는 함수나 튜플을 unpacking할 때 임시 변수로 사용
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def multi_returnx: | |
return x, x+1, x+3 | |
_, x_plus_1, _ = multi_return3 |
마무리
- 어렴풋이 알고있던 내용을 정리할 수 있는 기회였음
- _ 하나로 임시값을 코딩하는 것은 간단하게 코드를 깔끔하게 해줄 수 있는 방법인 것 같음
Reference
[1] Python Dunder Methods- A guide to use Python magic methods
'프로그래밍 언어 > python' 카테고리의 다른 글
numpy array를 사용할 때 for문을 피해야하는 이유 0 | 2022.07.26 |
---|---|
python 함수를 아름답게 사용하기 0 | 2022.07.26 |
unittest, Test-driven develope를 위한 라이브러리 0 | 2022.07.26 |
pyforest, 42개의 라이브러리를 한 줄의 코드로 import 0 | 2022.07.26 |
matplotlib 사용시 메모리 누수 0 | 2022.07.26 |