1 minute read

본 포스팅은 “윤성우의 열혈 파이썬 중급편” 책 내용을 기반으로 작성되었습니다. 잘못된 내용이 있을 경우 지적해 주시면 감사드리겠습니다.

19-1. 스페셜 메소드

스페셜 메소드: 이름을 명시하지 않고 다른 경로를 통해 or 상황에 따라 자동으로 호출되는 메소드

  • 형태: __name__
t = (1, 2, 3)

len(t) # == t.__len__()

itr = iter(t) # == t.__iter__()

for i in itr:
  print(i, end=' ')

s = str(t) # t.__str__()
s
(결과) 3
       1 2 3
       '(1, 2, 3)'

19-2. 클래스에 스페셜 메소드 정의하기

class Car:
  def __init__(self, id):
    self.id = id
  def __len__(self):
    return len(self.id)
  def __str__(self):
    return 'Vehicle number: ' + self.id

def main():
  c = Car("24모7777")
  print(len(c))  # == print(c.__len__())
  print(str(c))  # == print(c.__str__())

main()
(결과) 7
       Vehicle number: 24모7777

19-3. iterable 객체 되도록 하기

  • iterable 객체: iter 함수에 인자로 전달 가능한 객체. iter 함수에 들어가면 iterator 객체가 반환됨.
  • iterator 객체: next 함수에 인자로 전달 가능한 객체.
class Car:
  def __init__(self, id):
    self.id = id
  def __iter__(self):
    return iter(self.id)

def main():
  c = Car("24모7777")
  for i in c:
    print(i, end = ' ')

main()
(결과) 2 4 모 7 7 7 7

참고로 위 코드는 다음고 같다.

class Car:
  def __init__(self, id):
    self.id = id
  def __iter__(self):
    return iter(self.id)

def main():
  c = Car("24모7777")
  ir = c.__iter__()

  while True:
    try:
      i = next(ir)
      print(i, end = ' ')
    except StopIteration:
      break

main()
(결과) 2 4 모 7 7 7 7

19-4. iterator 객체가 되도록 하기

iterator 객체는 __next__ 메소드를 가지면서 다음 두 조건을 만족해야 한다.

  • 가지고 있는 값을 하나씩 반환
  • 반환할 값이 더 없으면 StopIteration 예외 발생시켜야 함
class coll:
  def __init__(self, d):
    self.ds = d
    self.cc = 0
  def __next__(self):
    if len(self.ds) <= self.cc:
      raise StopIteration
    self.cc += 1
    return self.ds[self.cc-1]
  
def main():
  co = coll([1, 2, 3, 4, 5])
  while True:
    try:
      i = next(co) # == co.__next__()
      print(i, end = ' ')
    except StopIteration:
      break
  
main()
(결과) 1 2 3 4 5

19-5. iterator 객체이자 iterable 객체가 되도록 하기

class Coll2:
  def __init__(self, d):
    self.ds = d
  def __next__(self):
    if len(self.ds) <= self.cc :
      raise StopIteration
    self.cc += 1
    return self.ds[self.cc-1]
  def __iter__(self):
    self.cc = 0
    return self  # Coll2의 객체인 co를 그대로 출력함

def main():
  co = Coll2([1, 2, 3, 4, 5])  # iter(co) is co 임!
  for i in co:
    print(i, end = ' ')
  for i in co:
    print(i, end = ' ')

main()
(결과) 1 2 3 4 5 1 2 3 4 5

Leave a comment