-
[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반응형'코딩 연습 > 코딩배우기' 카테고리의 다른 글
[python] 파이썬 datetime() 함수로 살아온 연월일 계산하기(코딩 연습) (0) 2020.09.23 [django] 파이썬 Django(장고) 템플릿 문법 (0) 2020.09.22 [python] 파이썬 재귀함수, 람다 함수 연습 (0) 2020.09.21 [python] 파이썬 datetime(), time(), localtime() (0) 2020.09.20 [python] 파이썬 함수의 위치 인자, 키워드 인자 언패킹 (0) 2020.09.19
