이전 시간에 봤었던

__init__ 이나

__del__ 함수들은

 

 

 

특수한 경우에 자동적으로

호출되는 함수들인데

 

 

 

위 두 함수 말고도 자주 사용되는

특수 함수들을 알아보자.

 

 

 

 


 

 

 

 

1. __str__ ( )

 

 

 

 

 

이 함수는

어떤 자료형을 문자열 자료형으로

변환할 때 사용하는 str() 함수를

사용하고

 

 

 

인자 값에, class의 생성자를 담은

변수라는 객체를 넣어 유용하게

사용할 수 있는 특수 함수로

 

 

 

매개변수로는 self를 받으면 되고

내부에 문자열을 만들어 return

해주면 된다.

 

 

 

 

 

 

 

 

 

 

 

 

굳이 __str__ 함수를 쓰지 않더라도

다른 이름의 method를 사용하여

얼마든지 문자열로 바꿀 수 있는

방법은 있지만

 

 

 

그럼에도 사용하는 이유는

파이썬 개발에서 개발자들끼리의

약속 같은 거라고 이해하면 되겠다.

 

 

 

 

 


 

 

 

 

 

비교 연산자를 사용할 때

호출하는 함수

 

 

 

 

eq : equal

ne : nor equal

gt : greater than

gte / ge : grater than or equal

lt : less then

le : less than or equal

 

 

 

 

각 키워드들은 다른 특수 함수와

동일하게 언더바 두 개를 앞뒤에

넣어 사용해 주면 되고

 

 

 

사용하고자 하는 비교 연산자에

해당하는 키워드의 함수를

선언하여 호출하면 된다.

 

 

 

 

class Student:
    def __init__(self, 이름, 나이):
        self.이름 = 이름
        self.나이 = 나이
    def __eq__(self, other):
        print("eq() 함수")
    def __ne__(self, other):
        print("ne() 함수")
    def __gt__(self, other):
        print("gt() 함수")
    def __ge__(self, other):
        print("gt() 함수")
    def __lt__(self, other):
        print("lt() 함수")
    def __le__(self, other):
        print("le() 함수")

student = Student("타쿠대디", 27)
student == student
student != student
student > student
student >= student
student < student
student <= student

 

 

 

 

 


 

 

 

 

 

물론 비교 연산 자체를 print 해줘도

되지만 그렇게 하는 경우 결괏값이

None으로 돌아온다!

 

 

 

class Student:
    def __init__(self, 이름, 나이):
        self.이름 = 이름
        self.나이 = 나이
    def __eq__(self, other):
        print("eq() 함수")
    def __ne__(self, other):
        print("ne() 함수")
    def __gt__(self, other):
        print("gt() 함수")
    def __ge__(self, other):
        print("gt() 함수")
    def __lt__(self, other):
        print("lt() 함수")
    def __le__(self, other):
        print("le() 함수")

student = Student("타쿠대디", 27)
print(student == student)
print(student != student)
print(student > student)
print(student >= student)
print(student < student)
print(student <= student

 

 

 

 

 


 

 

 

 

때문에 이 비교 연산 함수들은 리턴 값으로

반드시 True 혹은 False를 줘야 하는데

비교하고자 하는 함수와 매개변수를

return 값으로 넣어주면 된다.

 

 

class Student:
    def __init__(self, 이름, 나이):
        self.이름 = 이름
        self.나이 = 나이
    def __eq__(self, other):
       return (self.이름 == other.이름) and \
              (self.나이 == other.나이)
    def __ne__(self, other):
        return (self.이름 != other.이름) and \
              (self.나이 != other.나이)
    def __gt__(self, other):
        return (self.이름 > other.이름) and \
              (self.나이 > other.나이)
    def __ge__(self, other):
        return (self.이름 >= other.이름) and \
              (self.나이 >= other.나이)
    def __lt__(self, other):
        return (self.이름 < other.이름) and \
              (self.나이 < other.나이)
    def __le__(self, other):
        return self.이름 <= other.이름 and \
              (self.나이 <= other.나이)

student = Student("타쿠대디", 27)
print(student == student)
print(student != student)
print(student > student)
print(student >= student)
print(student < student)
print(student <= student)

 

 

 

 


 

 

 

 

 

위 키워드들 역시

파이썬 개발자들끼리의 약속으로

추후에 라이브러리 등을 만들어

다른 이에게 제공할 때

 

 

 

이처럼 약속된 키워드의 함수들을

사용하면 어떤 의도로 사용한 것인지

굳이 주석을 달지 않더라도 알기 때문에

서로가 사용하기 수월하다.

 

 

 

초보 단계에서는 클래스 내부의 코드를

어떻게 설계하고 어떻게 사용하는지,

또 내부의 패턴이 어떤 식으로 동작하는지

이해하고 익히기가 쉽지 않다.

 

 

 

지금은 그냥 이런 문법들이 있고

이런 식으로 쓰이는구나 정도로만

이해하고 넘어가도 충분하다.

 

 

 

계속 보고 계속 사용하다 보면 결국

익숙해져서 이해하는 날이 올 것이다.

 

 

 

 

728x90
반응형

+ Recent posts