[Python] 스페셜 메서드 (Special Method)

형이·2023년 11월 7일

Python

목록 보기
18/34
post-thumbnail

📝 스페셜 메서드

🖥️ 1. 스페셜 메서드란?

  • __로 시작해서 __로 끝나는 특수함수
  • 해당 메서드들을 구현하면 객체에 여러가지 파이썬 내장함수나 연산자에 원하는 기능을 적용 가능
class Sentence :
  def __init__(self, s) :
    self.words = s.split()

  def __len__(self) :  # len() 함수를 위한 스페셜 메서드
    return len(self.words)

s = Sentence('Somtimes bad things happlen to good people')
# len() : 길이값을 return 파이썬 내장 함수
print(len('Hello'))
print(len([1,2,3,4,5]))
print(s.words)
print(len(s.words))
print(len(s))

[결과]
5
5
['Somtimes', 'bad', 'things', 'happlen', 'to', 'good', 'people']
7
7
class Point :
  def __init__(self, x, y) :
    self.x = x
    self.y = y
  def __str__(self) :   # str() 스페셜 메서드 기능 오버라이딩
    return('{}, {}'.format(self.x, self.y))

p1 = Point(3, 4)
print(p1)
print(str(p1))    # str (클래스 객체) : object 객체
                  # str이 생략됐다.
                  # str에 다른 기능을 override
                  
[결과]
3, 4
3, 4

0개의 댓글