6.12 특수 메서드

  • magic 메서드라고도 불리며 __로 시작하고 끝난다.
    class Word():
    def __init__(self, text):
    self.text = text
    def equals(self, word2):
    return self.text.lower() == word2.text.lower()
    
    first = Word('ha')
    second = Word('HA')
    third = Word('eh')
    
    first.equals(second)
    

    True

    first.equals(third)
    

    False

    class Word():
    def __init__(self, text):
    self.text = text
    def __eq__(self, word2):
    return self.text.lower() == word2.text.lower()
    
    first = Word('ha')
    second = Word('HA')
    third = Word('eh')
    
    first == second
    

    True

    first == third
    

    False

    first
    

<main.Word at 0x7fb3345325f8>

class Word():
def __init__(self, text):
self.text = text
def __eq__(self, word2):
return self.text.lower() == word2.text.lower()
def __str__(self):
return self.text
def __repr__(self):
return "Word('" + self.text + "')"
first = Word('ha')
first

Word(‘ha’)

print(first)

ha

Comments