[파이썬을 파이썬답게] 클래스 인스턴스 출력하기 (string casting)

이상해씨·2024년 2월 14일
0

Python

목록 보기
18/21

클래스 인스턴스 출력하기 (string casting)

  • instance의 출력 형식을 지정하는 방법
  • print 안, class 바깥에서 출력 함수를 생성하여 format 지정하기
class Coord(object):
    def __init__(self, x, y):
        self.x, self.y = x, y

# print문 내부에서 format지정
point = Coord(1, 2)
print( '({}, {})'.format(point.x, point.y) ) 

# 또는 class 밖의 함수를 생성하여 지정
def print_coord(coord):
    print( '({}, {})'.format(coord.x, coord.y) )
print_coord(point)
  • __str__ 를 사용하여 class 내부에서 format 지정
class Coord(object):
    def __init__ (self, x, y):
        self.x, self.y = x, y
    def __str__ (self):
        return '({}, {})'.format(self.x, self.y)

point = Coord(1, 2)

참고

profile
공부에는 끝이 없다

0개의 댓글