본문 바로가기

TIL/개인공부

[Python] 파이썬 클래스 던더(dunder) 메소드

반응형

파이썬을 공부하면서 클래스에 언더바(_)를 앞뒤로 두개씩 붙혀서 함수를 생성하는 요소가 있는데, 원래는 생성자(__init__) 소멸자(__del__)만 신경쓰다가 또 다른 함수가 있는지 알아보았다.

 

사실 이 글을 작성할때까지만해도 이러한 함수가 어떤 이름을 갖고있는지 몰랐는데 이번에 알게되었다.

이름은 던더 메소드이고 어떤 곳은 매직 메소드라고도 한다. 던더라는건 double underbar에서 줄인 단어이다.

 

아래는 간단한 클래스 예시

class Person:
    def __init__(self, name):
    	self.name = name
    	print("생성자")
        
    def __del__(self):
    	print("소멸자")
    
    def print_name(self):
    	print(self.name)
        print("일반 함수")

 

이러한 던더 메소드는 다양하게 존재함

__new__ __str__ __repr__ __add__ __sub__ __mul__ __div__ __eq__ 등등... 

 

예시로 __add__ 라는 던더 메소드를 선언할경우 두개의 클래스를 더할때의 상황을 정의할수있다.

class StringAdder:
	def __init__(self, string):
    	self.string = string
        
    def __add__(self, other):
    	return self.string + other.string
        
    def __str__(self):
    	return self.string
        
s1 = StringAdder('Hello')
s2 = StringAdder('World')

print(s1 + s2)  # 출력: HelloWorld
print(s1, s2)   # 출력: Hello World

 

참고 자료

- https://wikidocs.net/192020

 

18. 던더메소드

파이썬에서 메소드 이름 양옆에 언더스코어`__`가 있는 경우, 이를 던더(Double Underscore, 이중 언더스코어)라고 합니다. 던더는 일반적으로 매직 메소드 또는 …

wikidocs.net

- https://blog.naver.com/youndok/222566232550

 

파이썬 클래스(class) 특수 메소드 - 더블언더(던더) 메소드(dunder method) 또는 매직 메소드(magic method

본 포스팅에서는 "파이썬 class 생성 및 객체지향 프로그래밍 용어 정리"에서 설명한 기본 개념...

blog.naver.com

 

반응형