Python - 문제 미리보기

문제 2051

medium
다음 코드에서 `__str__` 메서드의 실행 결과는?
```python
class Book:
def __init__(self, title, author):
self.title = title
self.author = author

def __str__(self):
return f"책: {self.title} (저자: {self.author})"

book1 = Book("파이썬 입문", "김코딩")
print(book1)
```
A. `<__main__.Book object at 0x...>`
B. `Book("파이썬 입문", "김코딩")`
C. `책: 파이썬 입문 (저자: 김코딩)`
D. 오류 발생

정답: C



`__str__` 메서드의 기능:

문자열 표현 제어:
⦁ 목적: 객체를 `print()` 할 때 어떻게 표시될지 정의
⦁ 자동 호출: `print(객체)` 또는 `str(객체)` 시 자동 실행
⦁ 사용자 친화적: 읽기 쉬운 형태로 객체 정보 제공

`__str__` 있을 때 vs 없을 때:

`__str__` 메서드가 없는 경우:
```python
class Book:
def __init__(self, title, author):
self.title = title
self.author = author

book1 = Book("파이썬 입문", "김코딩")
print(book1) # <__main__.Book object at 0x7f8b8c0d5f70>
```
⦁ 기본 출력: 클래스명과 메모리 주소 출력
⦁ 정보 부족: 객체의 실제 내용을 알 수 없음

`__str__` 메서드가 있는 경우:
```python
class Book:
def __init__(self, title, author):
self.title = title
self.author = author

def __str__(self):
return f"책: {self.title} (저자: {self.author})"

book1 = Book("파이썬 입문", "김코딩")
print(book1) # 책: 파이썬 입문 (저자: 김코딩)
```
⦁ 사용자 정의 출력: 개발자가 원하는 형태로 표시
⦁ 의미 있는 정보: 객체의 핵심 내용을 한눈에 파악 가능

💡 학습 팁

이 문제를 포함한 Python 과목의 모든 문제를 순차적으로 풀어보세요. 진행상황이 자동으로 저장되어 언제든지 이어서 학습할 수 있습니다.