__repr__ 메서드 구현하기
__str__ 외에도 Python 은 문자열 표현을 위한 또 다른 특수 메서드인 __repr__을 제공합니다. __str__이 사람이 읽을 수 있는 표현을 제공하기 위한 것이라면, __repr__은 가능한 경우 객체를 다시 생성하는 데 사용할 수 있는 객체의 모호하지 않은 표현을 제공하기 위한 것입니다.
__repr__ 메서드 이해하기
__repr__ 메서드는 객체에 대해 repr() 함수를 사용하거나 대화형 세션에서 객체를 표시할 때 호출됩니다. 이 메서드는 eval()에 전달될 때 (가능한 경우) 동등한 객체를 생성하는 문자열을 반환해야 합니다.
__repr__ 메서드를 포함하도록 Book 클래스를 업데이트해 보겠습니다.
-
편집기에서 book.py를 엽니다.
-
__repr__ 메서드를 포함하도록 코드를 업데이트합니다.
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return f'"{self.title}" by {self.author} ({self.pages} pages)'
def __repr__(self):
return f'Book("{self.title}", "{self.author}", {self.pages})'
## Create book objects
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", 180)
book2 = Book("To Kill a Mockingbird", "Harper Lee", 281)
## Print the books (uses __str__)
print("String representation (using __str__):")
print(book1)
print(book2)
## Get the representation (uses __repr__)
print("\nRepresentation (using __repr__):")
print(repr(book1))
print(repr(book2))
-
파일을 저장합니다.
-
스크립트를 실행합니다.
python3 book.py
다음과 같은 출력을 볼 수 있습니다.
String representation (using __str__):
"The Great Gatsby" by F. Scott Fitzgerald (180 pages)
"To Kill a Mockingbird" by Harper Lee (281 pages)
Representation (using __repr__):
Book("The Great Gatsby", "F. Scott Fitzgerald", 180)
Book("To Kill a Mockingbird", "Harper Lee", 281)
__str__과 __repr__의 차이점
__str__과 __repr__의 주요 차이점은 다음과 같습니다.
__str__은 사람이 읽을 수 있는 출력을 위한 것이고, __repr__은 개발자 및 디버깅을 위한 것입니다.
__str__이 정의되지 않았지만 __repr__이 정의된 경우, Python 은 str() 또는 print()에 대한 대체로 __repr__을 사용합니다.
__repr__은 이상적으로 eval()에 전달될 때 객체를 다시 생성할 수 있는 문자열을 반환해야 하지만, 이것이 항상 가능하거나 필요한 것은 아닙니다.
__repr__과 함께 eval() 함수 사용하기
올바르게 구현되면 __repr__에서 반환된 문자열을 eval()과 함께 사용하여 객체를 다시 생성할 수 있습니다. 이를 실제로 살펴보겠습니다.
-
repr_eval.py라는 새 파일을 생성합니다.
-
다음 코드를 추가합니다.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point at ({self.x}, {self.y})"
def __repr__(self):
return f"Point({self.x}, {self.y})"
## Create a point
p1 = Point(3, 4)
## Get the repr string
repr_str = repr(p1)
print(f"Representation: {repr_str}")
## Use eval to recreate the object
p2 = eval(repr_str)
print(f"Recreated object: {p2}")
## Verify they have the same values
print(f"p1.x = {p1.x}, p1.y = {p1.y}")
print(f"p2.x = {p2.x}, p2.y = {p2.y}")
-
파일을 저장합니다.
-
스크립트를 실행합니다.
python3 repr_eval.py
다음과 같은 출력을 볼 수 있습니다.
Representation: Point(3, 4)
Recreated object: Point at (3, 4)
p1.x = 3, p1.y = 4
p2.x = 3, p2.y = 4
이것은 __repr__에서 반환된 문자열과 eval() 함수를 사용하여 원래 객체를 다시 생성할 수 있음을 보여줍니다.
각 메서드를 언제 사용해야 할까요?
- 객체의 초기 상태를 설정하려면
__init__을 사용합니다.
- 최종 사용자를 위해 사람이 읽을 수 있는 표현을 제공하려면
__str__을 사용합니다.
- 개발자 및 디버깅을 위해 정확하고 모호하지 않은 표현을 제공하려면
__repr__을 사용합니다.
실습: 완전한 예시
세 가지 특수 메서드 모두를 사용하여 Rectangle 클래스를 만들어 보겠습니다.
-
rectangle.py라는 새 파일을 생성합니다.
-
다음 코드를 추가합니다.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
def __str__(self):
return f"Rectangle with width {self.width} and height {self.height}"
def __repr__(self):
return f"Rectangle({self.width}, {self.height})"
## Create rectangles
rect1 = Rectangle(5, 10)
rect2 = Rectangle(3, 7)
## Display information about the rectangles
print(f"Rectangle 1: {rect1}")
print(f"Area: {rect1.area()}")
print(f"Perimeter: {rect1.perimeter()}")
print(f"Representation: {repr(rect1)}")
print("\nRectangle 2: {0}".format(rect2))
print(f"Area: {rect2.area()}")
print(f"Perimeter: {rect2.perimeter()}")
print(f"Representation: {repr(rect2)}")
## Recreate a rectangle using eval
rect3 = eval(repr(rect1))
print(f"\nRecreated rectangle: {rect3}")
print(f"Is it the same area? {rect3.area() == rect1.area()}")
-
파일을 저장합니다.
-
스크립트를 실행합니다.
python3 rectangle.py
다음과 같은 출력을 볼 수 있습니다.
Rectangle 1: Rectangle with width 5 and height 10
Area: 50
Perimeter: 30
Representation: Rectangle(5, 10)
Rectangle 2: Rectangle with width 3 and height 7
Area: 21
Perimeter: 20
Representation: Rectangle(3, 7)
Recreated rectangle: Rectangle with width 5 and height 10
Is it the same area? True
이 예제는 세 가지 특수 메서드 (__init__, __str__, __repr__) 가 함께 작동하여 잘 설계된 클래스를 만드는 방법을 보여줍니다.