클래스 (4월 14일)

송영석·2023년 4월 15일
0

데이터스쿨 14기

목록 보기
4/18

클래스

  • class 키워드, 속성(변수), 기능(함수) 통해 만듦
  • 클래스는 또 다른 클래스를 상속해서 내 것처럼 사용 가능
  • 다중상속 : 2개 이상의 클래스를 상속
  • 추상클래스 : 상위 클래스에서 하위 클래스에 메서드 구현을 강요
    • 특정 기능을 상속을 받을 때 각자 알맞게 수정해서 쓰려고

객체

  • 속성 + 기능
  • 코드 재사용 및 모듈화에 좋음
  • 클래스에서 생성됨
  • 클래스의 생성자를 호출함
  • 클래스의 이름 첫글자는 대문자
  • 객체 속성은 변경 가능
  • 변수는 객체의 메모리 주소에 저장하고 이를 이용해서 객체를 참조함
  • 얕은복사와 깊은복사
    • 얕은복사 : 객체 주소를 복사, 객체 자체가 복사되지 않음
    • 깊은복사 : 객체 자체를 복사, 또 하나의 객체가 만들어짐

생성자

  • 객체가 생성될 때 생성자를 호출하면 init() 자동 호출됨
  • init() 속성을 초기화 함
  • 상위 클래스의 속성을 초기화하기 위해서 super()를 이용함

오버라이딩

  • 하위 클래스에서 상위 클래스의 메서드를 재정의(override)
18

<개념>

class Car:

    def __init__(self, color, length):
        self.color = color
        self.length = length

    def doStop(self):
        print("STOP!!")

    def doStart(self):
        print("START!!")

    def carInfo(self):
        print(f"self.color: {self.color}")
        print(f"self.length: {self.length}")

car1 = Car("red", 200)
car2 = Car("blue", 200)

car1.carInfo()
car1.doStop()
car1.doStart()

car2.carInfo()
car2.doStop()
car2.doStart()


<실습>

class Airplane:

    def __init__(self, color, length, weight):
        self.color = color
        self.length = length
        self.weight = weight

    def landing(self):
        print("Landing!!")

    def takeOff(self):
        print("Take-off!!")

    def airplaneInfo(self):
        print(f"self.color: {self.color}")
        print(f"self.length: {self.length}")
        print(f"self.weight: {self.weight}")

airplane1 = Airplane("yellow", 200, 300)
airplane2 = Airplane("blue", 210, 320)
airplane3 = Airplane("mint", 220, 340)
airplane4 = Airplane("red", 230, 360)
airplane5 = Airplane("white", 240, 380)

airplane1.airplaneInfo()
airplane1.landing()
airplane1.takeOff()

airplane2.airplaneInfo()
airplane2.landing()
airplane2.takeOff()

airplane3.airplaneInfo()
airplane3.landing()
airplane3.takeOff()

airplane4.airplaneInfo()
airplane4.landing()
airplane4.takeOff()

airplane5.airplaneInfo()
airplane5.landing()
airplane5.takeOff()
19

<객체 속성변경>
class PC:

    def __init__(self, name, cpu, memory, ssd):
        self.name = name
        self.cpu = cpu
        self.memory = memory
        self.ssd = ssd

    def excel(self):
        print("EXCEL RUN!!")

    def photoshop(self):
        print("PHOTOSHOP RUN!!")

    def pcInfo(self):
        print(f"self.name: {self.name}")
        print(f"self.cpu: {self.cpu}")
        print(f"self.memory: {self.memory}")
        print(f"self.ssd: {self.ssd}")

myPC = PC("myPC", "i5", "16G", "256G")
myPC.pcInfo()

friendPC = PC("friendPC", "i7", "32G", "512G")
friendPC.pcInfo()
--객체 속성 변경--
myPC.cpu = "i9"
myPC.memory = "64"
myPC.ssd = "1T"
myPC.pcInfo()


<실습>

class Calculator:

    def __init__(self):
        self.number1 = 0
        self.number2 = 0
        self.result = 0

    def add(self):
        self.result = self.number1 + self.number2
        return self.result

    def sub(self):
        self.result = self.number1 - self.number2
        return self.result

    def mul(self):
        self.result = self.number1 * self.number2
        return self.result

    def div(self):
        self.result = self.number1 / self.number2
        return self.result

calculator = Calculator()
calculator.number1 = 10
calculator.number2 = 20

print(f"calculator.add(): {calculator.add()}")
print(f"calculator.sub(): {calculator.sub()}")
print(f"calculator.mul(): {calculator.mul()}")
print(f"calculator.div(): {calculator.div()}")

calculator.number1 = 3
calculator.number2 = 5

print(f"calculator.add(): {calculator.add()}")
print(f"calculator.sub(): {calculator.sub()}")
print(f"calculator.mul(): {calculator.mul()}")
print(f"calculator.div(): {calculator.div()}")
20

class Robot:

    def __init__(self, color, height, weight):
        self.color = color
        self.height = height
        self.weight = weight

    def robotInfo(self):
        print(f"color: {self.color}")
        print(f"height: {self.height}")
        print(f"weight: {self.weight}")

rb1 = Robot("red", 200, 80)
rb2 = Robot("blue", 300, 120)
rb3 = rb1

rb1.robotInfo()
rb2.robotInfo()
rb3.robotInfo()

rb1.color = "gray"
rb1.height = 250
rb1.weight = 100
rb1.robotInfo()
rb2.robotInfo()
rb3.robotInfo()


<실습>

scores = [int(input("국어 점수 입력: ")),
          int(input("영어 점수 입력: ")),
          int(input("수학 점수 입력: "))]

print(scores)

copyScores = scores.copy()

for idx, score in enumerate(copyScores):
    afterScore = score * 1.1
    copyScores[idx] = 100 if afterScore > 100 else afterScore
    
print(copyScores)
print(f"이전 평균: {round(sum(scores) / len(scores), 2)}")
print(f"이후 평균: {round(sum(copyScores) / len(copyScores), 2)}")
21

<얕은 복사>

class TemCls:

    def __init__(self, n, s):
        self.number = n
        self.str = s

    def prnitClsInfo(self):
        print(f"sel.number: {self.number}")
        print(f"sel.str: {self.str}")

tc1 = TemCls(10, "Hello")
tc2 = tc1

tc1.prnitClsInfo()
tc2.prnitClsInfo()

tc2.number = 3.14
tc2.str = "Bye"

tc1.prnitClsInfo()
tc2.prnitClsInfo()


<깊은 복사>

class TemCls:

    def __init__(self, n, s):
        self.number = n
        self.str = s

    def prnitClsInfo(self):
        print(f"sel.number: {self.number}")
        print(f"sel.str: {self.str}")

import copy

tc1 = TemCls(10, "Hello")
tc2 = copy.copy(tc1)

tc1.prnitClsInfo()
tc2.prnitClsInfo()

tc2.number = 3.14
tc2.str = "Bye"

tc1.prnitClsInfo()
tc2.prnitClsInfo()


[list와 관련된 복사 방법]

scores = [9, 8, 7, 6, 5, 10]
scoresCopy =[]

<얕은 복사>
scoresCopy = scores
print(f"id(scores): {id(scores)}")
print(f"id(scoresCopy): {id(scoresCopy)}")

<깊은 복사1>
for s in scores:
    scoresCopy.append(s)

print(f"id(scores): {id(scores)}")
print(f"id(scoresCopy): {id(scoresCopy)}")

<깊은 복사2>
scoresCopy.extend(scores)

<깊은 복사3>
import copy

scoresCopy = scores.copy()

<깊은 복사4>
scoresCopy = scores[:]


<실습>

originalScore = [8.7, 9.1, 8.9, 9.0, 7.9, 9.5, 8.8, 8.3]
copyScore = originalScore.copy()

originalScore.sort()    #오름차순

copyScore.sort()
copyScore.pop(0)    # 가장 처음 요소 삭제
copyScore.pop()     # 맨 마지막 요소 삭제

print(f"originalScore: {originalScore}")
print(f"copyScore: {copyScore}")

originalTotal = sum(originalScore)
originalAverage = round(originalTotal / len(originalScore), 2)
print(f"originalTotal: {originalTotal}")
print(f"originalAverage: {originalAverage}")

copyTotal = round(sum(copyScore), 2)
copyAverage = round(copyTotal / len(copyScore), 2)
print(f"copyTotal: {copyTotal}")
print(f"copyAverage: {copyAverage}")

print(f"originalAverage - copyAverage: {round(originalAverage - copyAverage, 2)}")
22

<상속>

class NormalCar:

    def drive(self):
        print("[NormalCar] drive() called!!")

    def back(self):
        print("[NormalCar] back() called!!")

class TurboCar(NormalCar):

    def turbo(self):
        print("[TurboCar] turbo() called!!")

myTurboCar = TurboCar()
myTurboCar.drive()
myTurboCar.back()
myTurboCar.turbo()


<실습>

class CalculatorSuper:

    def add(self, n1, n2):
        return n1 + n2

    def sub(self, n1, n2):
        return n1 - n2

class CalculatorChild(CalculatorSuper):

    def mul(self, n1, n2):
        return n1 * n2

    def div(self, n1, n2):
        return n1 / n2

cal = CalculatorChild()
print(f"cal.add(10, 20): {cal.add(10, 20)}")
print(f"cal.sub(10, 20): {cal.sub(10, 20)}")
print(f"cal.mul(10, 20): {cal.mul(10, 20)}")
print(f"cal.div(10, 20): {cal.div(10, 20)}")
23

<생성자>

class Calculator:

    def __init__(self):
        print("[Calculator] __init__() called!!")

cal = Calculator()      # 변수를 활용해 생성자 호출

<__init__()>
class Calculator:

    def __init__(self, n1, n2):
        print("[Calculator] __init__() called!!")
        self.num1 = n1
        self.num2 = n2

cal = Calculator(10, 20)
print(f"cal.num1: {cal.num1}")
print(f"cal.num2: {cal.num2}")

class Calculator:

    def __init__(self):
        print("[Calculator] __init__() called!!")
        self.num1 = 10
        self.num2 = 100

cal = Calculator()
print(f"cal.num1: {cal.num1}")
print(f"cal.num2: {cal.num2}")

<super()>
class P_Class:

    def __init__(self, pNum1, pNum2):
        print("[P_Class] __init__() called!!")

        self.pNum1 = pNum1
        self.pNum2 = pNum2

class C_Class(P_Class):

    def __init__(self, cNum1, cNum2):
        print("[C_Class] __init__() called!!")

        # P_Class.__init__(self, cNum1, cNum2)
        super().__init__(cNum1, cNum2)

        self.cNum1 = cNum1
        self.cNum2 = cNum2

cls = C_Class(10, 20)

print(f'cls.cNum1: {cls.cNum1}')
print(f'cls.cNum2: {cls.cNum2}')

print(f'cls.pNum1: {cls.pNum1}')
print(f'cls.pNum2: {cls.pNum2}')
24

<실습>

class MidExam:

    def __init__(self, score1, score2, score3):
        print("[MidExam] __init__()")

        self.mid_korScore = score1
        self.mid_engScore = score2
        self.mid_matScore = score3

    def scores(self):
        print(f"mid_korScore: {self.mid_korScore}")
        print(f"mid_engScore: {self.mid_engScore}")
        print(f"mid_matScore: {self.mid_matScore}")


class EndExam(MidExam):

    def __init__(self, score1, score2, score3, score4, score5, score6):
        print("[EndExam] __init__()")

        super().__init__(score1, score2, score3)

        self.end_korScore = score4
        self.end_engScore = score5
        self.end_matScore = score6

    def scores(self):
        super().scores()

        print(f"end_korScore: {self.end_korScore}")
        print(f"end_engScore: {self.end_engScore}")
        print(f"end_matScore: {self.end_matScore}")

    def totalScore(self):

        total = self.mid_korScore + self.mid_engScore + self.mid_matScore
        total += self.end_korScore + self.end_engScore + self.end_matScore

        return total

    def averageScore(self):

        return self.totalScore() / 6

exam = EndExam(85, 90, 88, 75, 85, 95)
exam.scores()
print(f"Total: {exam.totalScore()}")
print(f"Average: {round(exam.averageScore(), 2)}")
25

<다중 상속>

class Car01:

    def drive(self):
        print("drive() method called!!")

class Car02:

    def turbo(self):
        print("turbo() method called!!")

class Car03:

    def fly(self):
        print("fly() method called!!")

class Car(Car01, Car02, Car03):

    def __init__(self):
        pass


myCar = Car()
myCar.drive()
myCar.turbo()
myCar.fly()


<실습>

class BasicCalculator:

    def add(self, n1, n2):
        return n1 + n2

    def sub(self, n1, n2):
        return n1 - n2

    def mul(self, n1, n2):
        return n1 * n2

    def div(self, n1, n2):
        return n1 / n2

class DevelopCalculator:

    def mod(self, n1, n2):
        return n1 % n2

    def flo(self, n1, n2):
        return n1 // n2

    def exp(self, n1, n2):
        return n1 ** n2

class Calculator(BasicCalculator, DevelopCalculator):

    def __init__(self):
        pass

cal = Calculator()

print(f"cal.add(10, 20): {cal.add(10, 20)}")
print(f"cal.sub(10, 20): {cal.sub(10, 20)}")
print(f"cal.mul(10, 20): {cal.mul(10, 20)}")
print(f"cal.div(10, 20): {cal.div(10, 20)}")

print(f"cal.mod(10, 20): {cal.mod(10, 20)}")
print(f"cal.flo(10, 20): {cal.flo(10, 20)}")
print(f"cal.exp(2, 5): {cal.exp(2, 5)}")
26

<오버라이딩>

class Robot:

    def __init__(self, c, h, w):
        self.color = c
        self.height = h
        self.weight = w

    def fire(self):
        print("총알 발사!!")

    def robotInfo(self):
        print(f"self.color: {self.color}")
        print(f"self.height: {self.height}")
        print(f"self.weight: {self.weight}")


class NewRobot(Robot):

    def __init__(self, c, h, w):
        super().__init__(c, h, w)

    def fire(self):
        print("레이저 발사!!")

myRobot = NewRobot("red", 180, 120)
myRobot.robotInfo()
myRobot.fire()


<실습>

class TriangleArea:

    def __init__(self, w, h):
        self.width = w
        self.height = h

    def triangleAreaInfo(self):
        print(f"width: {self.width}")
        print(f"height: {self.height}")

    def area(self):
        return self.width * self.height / 2


class NewTriangleArea(TriangleArea):

    def __init__(self, w, h):
        super().__init__(w, h)

    def area(self):
        return str(super().area()) + "㎠"

ta = NewTriangleArea(7, 5)
ta.triangleAreaInfo()
triangleArea = ta.area()
print(f"triangleArea: {triangleArea}")
27

<추상클래스>

from abc import ABCMeta
from abc import abstractmethod

class AirPlane(metaclass=ABCMeta):

    @abstractmethod
    def flight(self):
        pass

    def forward(self):
        print("전진")

    def backward(self):
        print("후진")


class Airliner(AirPlane):

    def __init__(self, c):
        self.color = c

    def flight(self):
        print("시속 400km/h 비행")

class fighterPlane(AirPlane):

    def __init__(self, c):
        self.color = c

    def flight(self):
        print("시속 700km/h 비행")


al = Airliner("red")
al.flight()
al.forward()
al.backward()

fl = fighterPlane("blue")
fl.flight()
fl.forward()
fl.backward()


<실습>

from abc import ABCMeta
from abc import abstractmethod

class Calculator(metaclass=ABCMeta):

    @abstractmethod
    def add(self, n1, n2):
        pass

    @abstractmethod
    def sub(self, n1, n2):
        pass

    @abstractmethod
    def mul(self, n1, n2):
        pass

    @abstractmethod
    def div(self, n1, n2):
        pass


class DevelopCalculator(Calculator):

    def add(self, n1, n2):
        print(n1 + n2)

    def sub(self, n1, n2):
        print(n1 - n2)

    def mul(self, n1, n2):
        print(n1 * n2)

    def div(self, n1, n2):
        print(n1 / n2)

    def mod(self, n1, n2):
        print(n1 % n2)

    def flo(self, n1, n2):
        print(n1 // n2)

cal = DevelopCalculator()
cal.add(10, 20)
cal.sub(10, 20)
cal.mul(10, 20)
cal.div(10, 20)
cal.mod(10, 20)
cal.flo(10, 20)
profile
매일매일 작성!!

0개의 댓글