연산자 중복 정의에 관련된 내용입니다. 저의 이전 블로그(noon.tistory.com)에서 포스팅했던 내용이고 C++로 구현했던 걸 python 으로 재 구현했던 내용입니다.
1. 연산자 중복(operator overloading)
아무튼 파이썬에서는 연산자 중복을
수치 연산자를 중복해서 사용해 연산자를 중복시킬 수 있습니다.
ADD(self,other) + 연산 SUB(self,other) - 연산 mul(self,other) * 연산 truediv(self,other) / 연산 mod_(self,other) % 연산 __lshift__(self,other) « 연산 __rshift__(self,other) » 연산 __and__(self,other) & 연산 __or__(self,other) | 연산 __xor__(self,other) ^ 연산 __abs__(self,other) abs() 연산
위 연산자 이외에도 더 있으며 클래스 내에서 이 연산자를 정의하게 되면 연산자 사용시 그에따른 행동을 수행하게 됩니다.
2.Operator Overloading Code(Python)
class GString: # 클래스 선언 def init(self,init = None): # 생성자 self.content = init
def __sub__(self,str): # - 연산자 정의
for i in str:
self.content = self.content.replace(i,'')
return GString(self.content)
def Remove(self,str):
return self.__sub__(str)
def __abs__(self):
return GString(self.content.upper())
def Print(self):
print(self.content)
g = GString(“Hello Debian”) g.Print() g -= “Debian” g.Print()