디필의 요모조모

파이썬 for Beginner 12장 연습문제 본문

Programming Language/Python

파이썬 for Beginner 12장 연습문제

Diphylleia12 2019. 12. 8. 19:54

1. 다음 중 클래스의 정의로 옳은 것은?

    ① 파이썬에서만 제공되는 특별한 기능이다.
    ② 객체지향 프로그래밍의 핵심 개념이다.
    ③ 클래스와 필드는 동일한 용어이다.
    ④ 클래스 안에는 변수를 포함할 수 있는데, 이를 메서드라고 한다.

 

2. 자동차 클래스를 생성하는 코드이다. 빈칸을 채우시오.

    class Car :

        color = ""

        speed = 0

 

        def upSpeed(self, value) :

            self.speed += value

 

        def downSpeed(self, value) :

            self.speed -= value

 

3. 인스턴스의 색상과 속도를 출력하는 코드이다. 빈칸을 채우시오.

    class Car :

        color = ""

        speed = 0

 

    myCar1 = Car()

    myCar1.color = "빨강"

    myCar1.speed = 30

 

    print("자동차1의 색상의 %s이며, 현재 속도는 %dkm입니다." % (myCar1.color, myCar1.speed))

 

4. 속도를 50으로 초기화하는 클래스의 생성자 코드이다. 빈칸을 채우시오.

    class Car :

        speed = 0

 

            생성자 코드

        def __init__(self) :

            self.speed = 50

 

5. Car의 상속을 받는 RVCar 클래스를 정의하는 코드이다. 빈칸을 채우시오.

    class Car :

        speed = 0

 

        def upSpeed(self, value) :

            self.speed = self.speed + value

 

    class RVCar(Car) :

        seatNum = 0

 

        def getSeatNum(self) :

            return self.seatNum

 

6. 다음 설명에 해당하는 메서드는?

    ① 소멸자라고도 하며 인스턴스가 삭제될 때 자동으로 호출된다.                  __del__() 메서드
    ② 인스턴스 사이의 덧셈 작업이 일어나면 실행되는 메서드이다.                  __add__() 메서드
    ③ 인스턴스를 print() 문으로 출력할 때 실행되는 메서드이다.                      __repr__() 메서드
    ④ 인스턴스 사이의 비교 연산자(<=)가 사용될 때 호출되는 메서드이다.         __le__() 메서드

 

7. 파이썬에서 추상 메서드 효과를 내려고 슈퍼 클래스의 메서드에 작성하는 구문은?

    raise NotImplementedError()

 

8. 다음 설명 중 틀린 것은?

    ① 파이썬은 멀티 스레드와 멀티 프로세싱을 지원한다.
    ② 파이썬에서 멀티 스레드의 생성은 threading.Thread() 메서드를 사용한다.
    ③ 파이썬에서 멀티 스레드는 start()로 시작되고, 멀티 프로세싱은 join()으로 시작된다.
    ④ 파이썬에서 멀티 스레드는 내부적으로 프로세서를 1개만 사용하지만, 멀티 프로세스는 프로세서를 여러 개 동시          에 사용한다.

 

9. (심화문제) 415쪽의 [응용예제02]를 수정해서 마우스 왼쪽 버튼을 더블클릭하면 마지막 원부터 제거하고, 마우스 가운데 버튼을 클릭하면 마지막 사각형부터 제거하도록 하자. 즉 누르는 버튼에 따라서 원과 사각형을 각각 삭제한다.

from tkinter import *
import math
import random

class Shape:
    color, width = '', 0
    shX1, shY1, shX2, shY2 = [0] * 4
    def drawShape(self):
        raise NotImplementedError()

class Rectangle(Shape):
    objects = None
    def __init__(self, x1, y1, x2, y2, c, w):
        self.shX1 = x1
        self.shY1 = y1
        self.shX2 = x2
        self.shY2 = y2
        self.color = c
        self.width = w
        self.drawShape()
       
    def __del__(self) :
        for obj  in self.objects :
            canvas.delete(obj)
               
    def drawShape(self) :
        sx1 = self.shX1; sy1 = self.shY1; sx2 = self.shX2; sy2 =self.shY2
        squreList = []        
        squreList.append(canvas.create_line(sx1, sy1, sx1, sy2, fill = self.color, width = self.width))
        squreList.append(canvas.create_line(sx1, sy2, sx2, sy2, fill = self.color, width = self.width))
        squreList.append(canvas.create_line(sx2, sy2, sx2, sy1, fill = self.color, width = self.width))
        squreList.append(canvas.create_line(sx2, sy1, sx1, sy1, fill = self.color, width = self.width))
        self.objects=squreList
       
class Circle(Shape) :
    objects = None
    def __init__(self,  x1, y1, x2, y2, c, w):
        self.shX1 = x1
        self.shY1 = y1
        self.shX2 = x2
        self.shY2 = y2
        self.color = c
        self.width = w
        self.drawShape()

    def __del__(self) :
        canvas.delete(self.objects)
 
    def drawShape(self) :
        sx1= self.shX1;   sy1= self.shY1;  sx2 = self.shX2;   sy2 = self.shY2
        self.objects = canvas.create_oval(sx1, sy1, sx2, sy2,
                                          outline = self.color,
                                          width = self.width)

def  getColor() :
    r = random.randrange(16, 256)
    g = random.randrange(16, 256)
    b = random.randrange(16, 256)
    return "#" + hex(r)[2:] + hex(g)[2:] + hex(b)[2:]

def getWidth() :
    return random.randrange(1, 9)

def  startDrawRect(event):
    global x1, y1, x2, y2, rectshape,cirshape
    x1 = event.x
    y1 = event.y

def endDrawRect(event):
    global x1, y1, x2, y2, rectshape,cirshape
    x2 = event.x
    y2 = event.y
    rect = Rectangle(x1, y1, x2, y2, getColor(), getWidth())
    rectshape.append(rect)

def  startDrawCircle(event):
    global x1, y1, x2, y2, rectshape,cirshape
    x1=event.x
    y1=event.y

def endDrawCircle(event):
    global x1, y1, x2, y2, rectshape,cirshape
    x2=event.x
    y2=event.y
    cir = Circle(x1, y1, x2, y2, getColor(), getWidth())
    cirshape.append(cir)

def deleteRectShape(event):
    global rectshape
    if len(rectshape) != 0 :
        dRS = rectshape.pop()
        del(dRS)

def deleteCirShape(event):
    global cirshape
    if len(cirshape) != 0 :
        dCS = cirshape.pop()
        del(dCS)

rectshape,cirshape = [],[]
window = None
canvas = None
x1, y1, x2, y2 = None, None, None, None

if __name__ == "__main__" :
    window=Tk()
    window.title("객체지향 그림판")
    canvas = Canvas(window, height = 300, width = 300)
    canvas.bind("<Button-1>", startDrawRect)
    canvas.bind("<ButtonRelease-1>", endDrawRect)
    canvas.bind("<Button-3>", startDrawCircle)
    canvas.bind("<ButtonRelease-3>", endDrawCircle)
    canvas.bind("<Double-Button-1>",deleteCirShape)
    canvas.bind("<Double-Button-2>",deleteRectShape)

    canvas.pack()
    window.mainloop()

9번 코드 실행 결과
마우스 왼쪽 버튼 더블클릭 결과
마우스 가운데 버튼 더블클릭 결과

Comments