6/13/2015

Operator Overloading for Python Code(파이썬에서의 연산자 중복)

연산자 중복 정의에 관련된 내용입니다. 저의 이전 블로그(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()




HAHWUL

Security engineer, Gopher and H4cker!

Share: | Coffee Me:

2 comments:

  1. choco pie, apple pie, graph pie, Yummy pie, pie sun 번역하면 파이 태양 태양파이 맛있나.

    ReplyDelete