ABOUT ME

IT와 컴퓨터 관련 팁, 파이썬 등과 아파트 정보, 일상적인 경험 등의 생활 정보를 정리해서 올리는 개인 블로그

  • [python] 파이썬 스페셜 메소드 (Special Method) 사용 예제
    코딩 연습/코딩배우기 2020. 9. 22. 15:30
    반응형

    파이썬 스페셜 메소드 (Special Method)

     

    ■ 인스턴스(객체) 생성 시 사용할 수 있는 스페셜 메소드 중 비교 연산자 사용할 때 호출하는 메소드 알아보기

    class Li:
        pass
    
    count = 0
    for i in dir(Li()):
        print(i, end=', ')
        count += 1
        if count % 5 == 0:
            print()
    
    ''' [dir(Li()) 출력 결과]
    __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__,
    '''
    

     

    # 위 스페셜 메소드 중 비교연산, __repr__, __add__ 등 알아보기 

    인스턴스 사이의 비교 연산자(<, <=, >, >=, ==, != 등) 사용할 때 호출하는 비교 메서드 
    : __ lt __( ), __ le __( ), __ gt __( ), __ ge __( ), __ eq __( ), __ ne __( )

    인스턴스(객체)를 print ( ) 문으로 출력할 때 실행하는 __ repr __( )

    인스턴스(객체) 사이에 덧셈 작업이 일어날 때 실행되는 __ add __( )

     

     

     

    class Line:
        def __init__(self, len):
            self.length = len
        
        def __repr__(self):
            return '선(line) 길이 : ' + str(self.length) + 'cm'
        
        def __add__(self, other):
            return self.length + other.length
        
        def __lt__(self, other):
            return self.length < other.length
        def __le__(self, other):
        
            return self.length <= other.length
    
        def __gt__(self, other):
            return self.length > other.length
    
        def __ge__(self, other):
            return self.length >= other.length
    
        def __eq__(self, other):
            return self.length == other.length
    
        def __ne__(self, other):
            return self.length != other.length
    
    
    line1 = Line(100)
    line2 = Line(110)
    
    print(line1)  # 선(line) 길이 : 100cm  --> __repr__ 호출
    print(line2) # 선(line) 길이 : 110cm   --> __repr__ 호출
    
    print(line1.__add__(line2))  # 210
    print(line1.__lt__(line2))  # True
    print(line1.__le__(line2))  # True
    print(line1.__gt__(line2))  # False
    print(line1.__ge__(line2))  # False
    print(line1.__eq__(line2))  # False
    print(line1.__ne__(line2))  # True
    
    

     

    good4me.co.kr

    반응형
Designed by goodthings4me.