[Python] 11-2장 매직 메소드(__str__()), self, 객체 안의 객체, 상속

__str__() 메소드

- 객체의 데이터를 문자열로 변환할 때 사용

- print(인스턴스) 출력할 때 자동적으로 호출됨

class Car:
    def __init__(self, speed, color, model):
        self.speed = speed
        self.color = color
        self.model = model
    
    def drive(self):
        self.speed = 60
        
    def __str__(self):
        msg = "속도 = "+str(self.speed)+" 색상 = "+self.color+" 모델 = "+self.model
        return msg
        
myCar = Car(0, "red", "SUV")
print(myCar)  # 속도 = 0 색상 = red 모델 = SUV

 

- 참고로  __str__() 메소드 없이 그냥 인스턴스 출력 시,

print(myCar)  # <__main__.Car object at 0x00000208DE094148>

 

 

 

self

- 어떤 객체가 메소드를 호출했는지 알려줌

- 메소드 호출할 때 '인스턴스.메소드()' 같은 형식을 사용하고 인스턴스가 self로 전달

 

 

 

객체 안의 객체

- 생성자 안에서 객체 생성해서 인스턴스에 저장

class Car:
    def __init__(self):
        self.speed = 100
        self.color = "red"
        self.model = "SUV"
        self.turtle = Turtle()  # turtle 객체 생성
        
    def drive(self):
        self.turtle.forward(self.speed)
        
myCar = Car()
myCar.drive()

 

 

 

상속

- 클래스 정의할 때 부모 클래스 지정

- 자식 클래스는 부모 클래스의 변수와 메소드 사용, 변경 가능

class 클래스이름(부모클래스):
    # 변수 생성
    # 메소드 정의
from turtle import *
class newTurtle(Turtle):  # 부모 클래스는 Turtle
    def glow(self):
        self.fillcolor("red")
        
myTurtle = newTurtle()
myTurtle.shape("turtle")
myTurtle.glow()