Python 공부 기록-5

김시헌·2025년 3월 28일

클로저

클로저는 함수 안에 내부 함수를 구현하고 그 내부 함수를 리턴하는 함수를 말한다. 이때 외부 함수는 자신이 가진 변숫값 등을 내부 함수에 전달할 수 있다.

클래스를 이용해 특정 값을 미리 설정하고 그다음부터 mul() 메서드를 사용하면 원하는 형태로 호출할 수 있다. call 메서드를 이용하여 다음과 같이 개선할 수도 있다.

코드

class Mul:
  def __init__(self,m):
    self.m = m
  
  def __call__(self, n):
    return self.m*n

if __name__ == "__main__":
  mul3=Mul(3)
  mul5=Mul(5)

  print(mul3(10))
  print(mul5(10))

실행 결과
30
50

데코레이터

Account 인스턴스에 저장된 정보를 출력하는 display_info() 메서드를 추가하세요. 잔고는 세자리마다 쉼표를 출력하세요.

코드

import random

class Account:
    account_count = 0

    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
        self.bank = "SC은행"

        num1 = random.randint(0, 999)
        num2 = random.randint(0, 99)
        num3 = random.randint(0, 999999)

        num1 = str(num1).zfill(3)
        num2 = str(num2).zfill(2)
        num3 = str(num3).zfill(6)
        self.account_number = num1 + '-' + num2 + '-' + num3
        Account.account_count += 1

    @classmethod
    def get_account_num(cls):
        print(cls.account_count)

    def deposit(self, amount):
        if amount >= 1:
            self.balance += amount

    def withdraw(self, amount):
        if self.balance > amount:
            self.balance -= amount

    def display_info(self):
        print("은행이름: ", self.bank)
        print("예금주: ", self.name)
        print("계좌번호: ", self.account_number)
        print("잔고: ", f"{self.balance:,}")

p = Account("파이썬", 10000)
p.display_info()

실행 결과
은행이름: SC은행
예금주: 파이썬
계좌번호: 986-28-465098
잔고: 10,000

입금 횟수가 5회가 될 때 잔고를 기준으로 1%의 이자가 잔고에 추가되도록 코드를 변경해보세요.

코드

import random

class Account:
    account_count = 0

    def __init__(self, name, balance):
        self.deposit_count = 0

        self.name = name
        self.balance = balance
        self.bank = "SC은행"

        num1 = random.randint(0, 999)
        num2 = random.randint(0, 99)
        num3 = random.randint(0, 999999)

        num1 = str(num1).zfill(3)
        num2 = str(num2).zfill(2)
        num3 = str(num3).zfill(6)

        self.account_number = num1 + '-' + num2 + '-' + num3
        Account.account_count += 1

    @classmethod
    def get_account_num(cls):
        print(cls.account_count)

    def deposit(self, amount):
        if amount >= 1:
            self.balance += amount

            self.deposit_count += 1
            if self.deposit_count % 5 == 0:
                self.balance = (self.balance * 1.01)

    def withdraw(self, amount):
        if self.balance > amount:
            self.balance -= amount

    def display_info(self):
        print("은행이름: ", self.bank)
        print("예금주: ", self.name)
        print("계좌번호: ", self.account_number)
        print("잔고: ", f"{self.balance:,}")

p = Account("파이썬", 10000)
p.deposit(10000)
p.deposit(10000)
p.deposit(10000)
p.deposit(5000)
p.deposit(5000)
print(p.balance)

실행 결과
50500.0

Account 클래스로부터 3개 이상 인스턴스를 생성하고 생성된 인스턴스를 리스트에 저장해보세요.

코드

import random

class Account:
    account_count = 0

    def __init__(self, name, balance):
        self.deposit_count = 0

        self.name = name
        self.balance = balance
        self.bank = "SC은행"

        num1 = random.randint(0, 999)
        num2 = random.randint(0, 99)
        num3 = random.randint(0, 999999)

        num1 = str(num1).zfill(3)
        num2 = str(num2).zfill(2)
        num3 = str(num3).zfill(6)

        self.account_number = num1 + '-' + num2 + '-' + num3
        Account.account_count += 1

    @classmethod
    def get_account_num(cls):
        print(cls.account_count)

    def deposit(self, amount):
        if amount >= 1:
            self.balance += amount

            self.deposit_count += 1
            if self.deposit_count % 5 == 0:
                self.balance = (self.balance * 1.01)

    def withdraw(self, amount):
        if self.balance > amount:
            self.balance -= amount

    def display_info(self):
        print("은행이름: ", self.bank)
        print("예금주: ", self.name)
        print("계좌번호: ", self.account_number)
        print("잔고: ", f"{self.balance:,}")

data = []
k = Account("KIM", 10000000)
i = Account("LEE", 10000)
p = Account("PARK", 10000)

data.append(k)
data.append(i)
data.append(p)

print(data)

실행 결과
[<main.Account object at 0x7d8d6b882250>, <main.Account object at 0x7d8d6b881d90>, <main.Account object at 0x7d8d6b9f6a10>]

반복문을 통해 리스트에 있는 객체를 순회하면서 잔고가 100만원 이상인 고객의 정보만 출력하세요.

코드

import random

class Account:
    account_count = 0

    def __init__(self, name, balance):
        self.deposit_count = 0

        self.name = name
        self.balance = balance
        self.bank = "SC은행"

        num1 = random.randint(0, 999)
        num2 = random.randint(0, 99)
        num3 = random.randint(0, 999999)

        num1 = str(num1).zfill(3)
        num2 = str(num2).zfill(2)
        num3 = str(num3).zfill(6)

        self.account_number = num1 + '-' + num2 + '-' + num3
        Account.account_count += 1

    @classmethod
    def get_account_num(cls):
        print(cls.account_count)

    def deposit(self, amount):
        if amount >= 1:
            self.balance += amount

            self.deposit_count += 1
            if self.deposit_count % 5 == 0:
                self.balance = (self.balance * 1.01)

    def withdraw(self, amount):
        if self.balance > amount:
            self.balance -= amount

    def display_info(self):
        print("은행이름: ", self.bank)
        print("예금주: ", self.name)
        print("계좌번호: ", self.account_number)
        print("잔고: ", f"{self.balance:,}")

data = []
k = Account("KIM", 10000000)
i = Account("LEE", 10000)
p = Account("PARK", 10000)

data.append(k)
data.append(i)
data.append(p)

for c in data:
  if c.balance >= 1000000:
    c.display_info()

실행 결과
은행이름: SC은행
예금주: KIM
계좌번호: 679-47-629578
잔고: 10,000,000

입금과 출금 내역이 기록되도록 코드를 엡데이트 하세요. 입금 내역과 출금 내역을 출력하는 deposit_history와 withdraw_history 메서드를 추가하세요.

코드

import random

class Account:
    account_count = 0

    def __init__(self, name, balance):
        self.deposit_count = 0
        self.deposit_log = []
        self.withdraw_log = []

        self.name = name
        self.balance = balance
        self.bank = "SC은행"

        num1 = random.randint(0, 999)
        num2 = random.randint(0, 99)
        num3 = random.randint(0, 999999)

        num1 = str(num1).zfill(3)
        num2 = str(num2).zfill(2)
        num3 = str(num3).zfill(6)
        self.account_number = num1 + '-' + num2 + '-' + num3
        Account.account_count += 1

    @classmethod
    def get_account_num(cls):
        print(cls.account_count)

    def deposit(self, amount):
        if amount >= 1:
            self.deposit_log.append(amount)
            self.balance += amount

            self.deposit_count += 1
            if self.deposit_count % 5 == 0:
                self.balance = (self.balance * 1.01)

    def withdraw(self, amount):
        if self.balance > amount:
            self.withdraw_log.append(amount)
            self.balance -= amount

    def display_info(self):
        print("은행이름: ", self.bank)
        print("예금주: ", self.name)
        print("계좌번호: ", self.account_number)
        print("잔고: ", self.balance)

    def withdraw_history(self):
        for amount in self.withdraw_log:
            print(amount)

    def deposit_history(self):
        for amount in self.deposit_log:
            print(amount)


k = Account("Kim", 1000)
k.deposit(100)
k.deposit(200)
k.deposit(300)
k.deposit_history()

k.withdraw(100)
k.withdraw(200)
k.withdraw_history()

실행 결과
100
200
300
100
200

다음 코드가 동작하도록 차 클래스를 정의하세요.

코드

>> car =(2,1000)
>> car.바퀴
2
>> car.가격
1000

정답 코드

class:
    def __init__(self, 바퀴, 가격):
        self.바퀴 = 바퀴
        self.가격 = 가격

car =(2, 1000)

print(car.바퀴)
print(car.가격)

실행 결과
2
1000

차 클래스를 상속받은 자전차 클래스를 정의하세요.

코드

class:
  def __init__(self, 바퀴, 가격):
        self.바퀴 = 바퀴
        self.가격 = 가격

class 자전차():
  pass

car =(2, 1000)

print(car.바퀴)
print(car.가격)

다음 코드가 동작하도록 자전차 클래스를 정의하세요. 단 자전차 클래스는 차 클래스를 상속받습니다.

코드

>> bicycle = 자전차(2, 100)
>> bicycle.가격
100

정답 코드

class:
  def __init__(self, 바퀴, 가격):
        self.바퀴 = 바퀴
        self.가격 = 가격

class 자전차():
  def __init__(self, 바퀴, 가격):
        self.바퀴 = 바퀴
        self.가격 = 가격

bicycle = 자전차(2, 100)
print(bicycle.가격)

실행 결과
100

다음 코드가 동작하도록 자전차 클래스를 정의하세요. 단 자전차 클래스는 차 클래스를 상속받습니다.

코드

>> bicycle = 자전차(2, 100, "시마노")
>> bicycle.구동계
시마노

정답 코드

class:
  def __init__(self, 바퀴, 가격):
        self.바퀴 = 바퀴
        self.가격 = 가격

class 자전차():
  def __init__(self, 바퀴, 가격, 구동계):
      super().__init__(바퀴, 가격)
      self.구동계 = 구동계

bicycle = 자전차(2, 100, "시마노")
print(bicycle.구동계)
print(bicycle.바퀴)

실행 결과
시마노
2

다음 코드가 동작하도록 차 클래스를 상속받는 자동차 클래스를 정의하세요.

코드

>> car = 자동차(4, 1000)
>> car.정보()
바퀴수 4
가격 1000

정답 코드

class:
  def __init__(self, 바퀴, 가격):
        self.바퀴 = 바퀴
        self.가격 = 가격

class 자동차():
  def __init__(self, 바퀴, 가격):
      super().__init__(바퀴, 가격)

  def 정보(self):
    print("바퀴수", self.바퀴)
    print("가격", self.가격)

car = 자동차(4, 1000)
car.정보()

실행 결과
바퀴수 4
가격 1000

다음 코드가 동작하도록 차 클래스를 수정하세요

코드

>> bicycle = 자전차(2, 100, "시마노")
>> bicycle.정보()
바퀴수 2
가격 100

정답 코드

class:
  def __init__(self, 바퀴, 가격):
        self.바퀴 = 바퀴
        self.가격 = 가격

  def 정보(self):
        print("바퀴수 ", self.바퀴)
        print("가격 ", self.가격)

class 자동차():
  def __init__(self, 바퀴, 가격):
        super().__init__(바퀴, 가격)

class 자전차():
  def __init__(self, 바퀴, 가격, 구동계):
        super().__init__(바퀴, 가격)
        self.구동계 = 구동계

bicycle = 자전차(2, 100, "시마노")
bicycle.정보()

실행 결과
바퀴수 2
가격 100

자전차의 정보() 메서드로 구동계 정보까지 출력하도록 수정해보세요.

코드

>> bicycle = 자전차(2, 100, "시마노")
>> bicycle.정보()
바퀴수 2
가격 100
구동계 시마노

정답 코드

class:
    def __init__(self, 바퀴, 가격):
        self.바퀴 = 바퀴
        self.가격 = 가격

    def 정보(self):
        print("바퀴수 ", self.바퀴)
        print("가격 ", self.가격)

class 자동차():
    def __init__(self, 바퀴, 가격):
        super().__init__(바퀴, 가격)

class 자전차():
    def __init__(self, 바퀴, 가격, 구동계):
        super().__init__(바퀴, 가격)
        self.구동계 = 구동계

    def 정보(self):
        super().정보()
        print("구동계 ", self.구동계)

bicycle = 자전차(2, 100, "시마노")
bicycle.정보()

실행 결과
바퀴수 2
가격 100
구동계 시마노

다음 코드의 실행 결과를 예상해보세요.

코드

class 부모:
  def 호출(self):
    print("부모호출")

class 자식(부모):
  def 호출(self):
    print("자식호출")= 자식().호출()

정답 코드

class 부모:
  def 호출(self):
    print("부모호출")

class 자식(부모):
  def 호출(self):
    print("자식호출")= 자식().호출()

실행 결과
자식호출

0개의 댓글