본문 바로가기

Python

[Python] __repr__ 메소드에 대해 알아보자

__repr__ 메소드는 Python의 매직 메소드 중 하나로, 객체의 공식적인 문자열 표현을 정의하는데 사용됩니다.

주로 디버깅이나 로그 기록 시, 객체의 정보를 쉽게 확인할 수 있도록 도와주며, repr()함수나 인터프리터에서 객체를 출력할 때 호출됩니다.

__repr__ 메서드의 사용법

__repr__ 메서드는 클래스 내부에 정의되며, 다음과 같은 형식으로 작성됩니다:

python

def __repr__(self):
    return "Your string representation"

여기서 self는 현재 객체를 참조합니다. 메서드 내에서 객체의 속성을 사용하여 문자열을 구성할 수 있습니다.

예제

아래는 Todo 클래스의 __repr__ 메서드를 사용하는 예제입니다:

python

class Todo:
    def __init__(self, id, contents, is_done):
        self.id = id
        self.contents = contents
        self.is_done = is_done

    def __repr__(self):
        return f"Todo(id={self.id}, contents='{self.contents}', is_done={self.is_done})"

# 객체 생성
todo1 = Todo(1, "Learn Python", False)
todo2 = Todo(2, "Write code", True)

# __repr__ 메서드 호출
print(repr(todo1))  # 출력: Todo(id=1, contents='Learn Python', is_done=False)
print(repr(todo2))  # 출력: Todo(id=2, contents='Write code', is_done=True)

내 코드 예시

from sqlalchemy import Boolean, Column, Integer, String

from sqlalchemy.orm import declarative_base



# test

from sqlalchemy import select

from connection import SessionFactory




Base = declarative_base() # ORM을 사용하기 위한 Base 클래스 생성




class Todo(Base):

__tablename__ = "todo" # todos 테이블 생성(없으면 생성, 있으면 사용)



id = Column(Integer, primary_key=True, index=True)

contents = Column(String(256), nullable=False)

is_done = Column(Boolean, nullable=False)



def __repr__(self): # 어떤 Todo 객체인지 확인하기 위해, __repr__ 메서드를 오버라이딩하여 사용

return f"Todo: {self.id}, {self.contents}, {self.is_done}"




if __name__ == "__main__":

session = SessionFactory()

todo = list(session.scalars(select(Todo))) # todos 테이블의 모든 데이터를 조회



for t in todo:

print(t)

 

실행 결과