
[ Python ] 파이썬에서 __str__과 __repr__에 대해 알아보자
sangjuns
·2022. 1. 19. 14:31
__str__과 __repr__에 대해 알아본 이유
- 웹 공부를 해나가면서 Python Flask로 짜여진 코드를 많이 읽는다. C언어와는 다르게 파이썬에서는 Class를 이용한 OOP코딩을 지향하시는 분들이 많다. 아래 코드는 드림핵에서 발췌해온 코드이다. 단순히 SQL을 쓰고 User라는 DB를 클래스화 시켜놨다.
객체의 다른 함수들은 그냥 평범한 메소드이다. 하지만 __repr__, __init__이렇게 언더라인 두 개가 붙어 있는 함수들은 특별한 의미를 가지고 있는 것 같았다. 예를 들어 __init__은 객체를 선언했을 때 생성자 역할을 하여 객체들의 값들을 초기화 시켜준다.
하지만 __repr__는 뭐하는 친구인지 궁금했다.
from sqlalchemy import Column, Integer, String, DateTime
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()#https://www.stechstar.com/user/zbxe/AlgorithmPython/35217
class User (Base):
__tablename__ = 'users'#테이블 이름은 users
id = Column(Integer, primary_key=True)#테이블 id username password occupation level목록들이 있다.
username = Column(String)
password = Column(String)
occupation = Column(String)
level = Column(Integer)
def __repr__(self):
return "<User(username='%s', level='%d')>" % \
(self.username, self.level)
@classmethod
def get_id(cls):
return User.id
@classmethod
def find_by_username(cls, session, username):
return session.query(User).filter(User.username == username).one()
@classmethod
def find_by_occupation(cls, session, occupation):
return session.query(User).filter(User.occupation == occupation).limit(10).all()
그래서 __str__이랑 __repr__가 뭔데?
- __str__은 사용자가 알아보기 쉽게 출력해주는 것이고 __repr__은 인터프리터가 알아보기 쉽게 출력해주는 것이다.
Class 안에 __str__과 __repr__를 쓰는 이유는 짧게 요약하자면 print()함수를 이용해 객체를 찍어볼때 원하는 값으로 나오도록 원래 str과 repr함수를 덮어쓰는 것(Override)이다.
즉, eval()함수 안에 넣어서 바로 실행하게 할 수 있는 것이 __repr__이고 그냥 문자열 자체로 결과만 보는 것이 __str__이다.
아직도 모르겠다면 아래 영상을 보자
아래 영상을 요약하면 이렇다.
__repr__함수는 eval함수에 넣었을 때 바로 코드로 해석되서 실행되는 것이고
__str__함수는 eval이나 인터프리터에서 넣었을때 그냥 문자열 자체로 인식되는 것이다.
__repr__함수가 eval에서 바로 실행되게 해서 어떤 점이 좋은가하면 디버깅할 때 유용하게 이용할 수 있다고 한다.
https://www.youtube.com/watch?v=5cvM-crlDvg
'프로그래밍' 카테고리의 다른 글
Makefile 작성법 정리 (0) | 2022.03.22 |
---|---|
[ AWS ] 도커를 이용해 AWS에서 배포하기 (0) | 2022.01.21 |
[ Network ] PC에서 모바일 패킷 캡쳐 방법 (0) | 2022.01.06 |
[ Network ] 네떡 종강 전 마지막 과제.. (0) | 2021.12.20 |
[Android] 안드로이드 프로젝트를 위한 잡지식들 (4) | 2021.11.14 |