2025-03-28

장상희·2025년 3월 28일

파이썬

목록 보기
4/31
post-thumbnail

2025-03-28

# closure.py
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))  # 30 출력
    print(mul5(10))  # 50 출력
# decorator.py
import time

def elapsed(original_func):   # 기존 함수를 인수로 받는다.
    def wrapper():
        start = time.time()
        result = original_func()    # 기존 함수를 수행한다.
        end = time.time()
        print("함수 수행시간: %f 초" % (end - start))  # 기존 함수의 수행시간을 출력한다.
        return result  # 기존 함수의 수행 결과를 리턴한다.
    return wrapper

def myfunc():
    print("함수가 실행됩니다.")

decorated_myfunc = elapsed(myfunc)
decorated_myfunc()
import random

class Account:
    # class variable
    account_count = 0# 이 클래스는 변수로 전체계좌의 수를 추척합니다 이변수는 모든 Account 객체가 공유한다 새로운 Account 객체가 추가될때마다 이변수는 1씩 증가한다

    def __init__(self, name, balance):
        self.name = name
        self.balance = balance
        self.bank = "SC은행" //#sc은행으로 고정됨

        # 3-2-6
        num1 = random.randint(0, 999)
        num2 = random.randint(0, 99)
        num3 = random.randint(0, 999999)

        num1 = str(num1).zfill(3)  # 0~999 사이의 난수
        num2 = str(num2).zfill(2)  # 0~99 사이의 난수
        num3 = str(num3).zfill(6)  # 0~999999 사이의 난수
        #각 난수들은 zfill()메서드를 사용해서 자릿수를 맞추어 3자리, 2자리, 6자리로 설정된다
        self.account_number = num1 + '-' + num2 + '-' + num3  # 001-01-000001
        Account.account_count += 1#생성되는 객체의 수를 세어주는 

    @classmethod
    #classmethod 데코레이터는 이 메서드가 클래스에 속하게 만듭니다
    #get_account_num은 현재까지 생선된 Account 객체의 수를 출력합니다
    def get_account_num(cls):
        print(cls.account_count)  # Account.account_count

    def deposit(self, amount):#이 메서드는 계좌에 입금을 처리합니다 amount가 1이상인 경우에만 잔액에 amount를 더합니다
        if amount >= 1:
            self.balance += amount

    def withdraw(self, amount):#이 메서드는 계좌에서 출금을 처리한다 잔액이 출금할 금액보다 많은 경우에만 출금이 가능하고 출금후에는 잔액에서 amount만큼 차감된다
        if self.balance > amount:
            self.balance -= amount
            

k = Account("kim", 100)
k.deposit(100)
k.withdraw(90)
print(k.balance)

클로저&데코레이터

  • 클로저는 내부 함수가 외부 함수의 변수에 접근할 수 있는 특성을 의미하며, 함수가 반환되더라도 그 변수들을 기억하고 사용할 수 있습니다.
  • 데코레이터는 클로저를 활용하여 함수를 확장하거나 수정하는 방법입니다. 데코레이터는 기존 함수에 새로운 기능을 추가하고, 클로저를 사용하여 이를 구현합니다.
import random

class Account:
    # class variable
    account_count = 0

    def __init__(self, name, balance):
        self.deposit_count = 0# 입금횟수를 세어준다
        self.name = name
        self.balance = balance
        self.bank = "SC은행"

        # 3-2-6
        num1 = random.randint(0, 999)
        num2 = random.randint(0, 99)
        num3 = random.randint(0, 999999)

        num1 = str(num1).zfill(3)  # 1 -> '1' -> '001'
        num2 = str(num2).zfill(2)  # 1 -> '1' -> '01'
        num3 = str(num3).zfill(6)  # 1 -> '1' -> '0000001'
        self.account_number = num1 + '-' + num2 + '-' + num3  # 001-01-000001
        Account.account_count += 1

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

    def deposit(self, amount):
        if amount >= 1:
            self.balance += amount
							
            self.deposit_count += 1#입금할때마다 해당 계좌에 1식 횟수가 충첩됩니다
            if self.deposit_count % 5 == 0:         # 5, 10, 15
                # 이자 지금
                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)
l = Account("LEE", 10000)
z = Account("PARK", 10000)
data.append(k)#리스트 안에 사용자를 넣는다
data.append(l)
data.append(z)

for c in data:#c번동안 데이터를 돌려가면서 확인한다
    if c.balance >= 1000000:#c번째 데이터에 있는 잔액이 100000000보다 큰지 확인해준다
        c.display_info()#위 조건에 맞는 예금주를 출력한다

l.display_info()
k.display_info()
z.display_info()
import random

class Account:
    # class variable
    account_count = 0

    def __init__(self, name, balance):
        self.deposit_count = 0# 입금횟수를 세어준다
        self.name = name
        self.deposit_log = []#입금을 기록해주는 리스트
        self.withdraw_log = []#출금을 기록해주는 리스트
        self.balance = balance
        self.bank = "SC은행"

        # 3-2-6
        num1 = random.randint(0, 999)
        num2 = random.randint(0, 99)
        num3 = random.randint(0, 999999)

        num1 = str(num1).zfill(3)  # 1 -> '1' -> '001'
        num2 = str(num2).zfill(2)  # 1 -> '1' -> '01'
        num3 = str(num3).zfill(6)  # 1 -> '1' -> '0000001'
        self.account_number = num1 + '-' + num2 + '-' + num3  # 001-01-000001
        Account.account_count += 1

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

    def deposit(self, amount):
        if amount >= 1:
            self.deposit_log.append(amount)#deposit리스트안에 입금한 amount값을 넣어줌
            self.balance += amount

            self.deposit_count += 1#입금할때마다 해당 계좌에 1식 횟수가 충첩됩니다
            if self.deposit_count % 5 == 0:         # 5, 10, 15
                # 이자 지금
                self.balance = (self.balance * 1.01)

    def withdraw(self, amount):
        if self.balance > amount:
           self.withdraw_log.append(amount)#withdraw_log리스트안에 출금한 amount값을 넣어줌
           self.balance -= amount
    
    def withdraw_history(self):
        for amount in self.withdraw_log:
            print(amount)

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

            
    def display_info(self):
        print("은행이름: ", self.bank)#은행이름
        print("예금주: ", self.name)#예금주
        print("계좌번호: ", self.account_number)#계좌번호
        print("잔고: ", f"{self.balance:,}")#잔액을 출력해주면서 ,을 찍어줌
    
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()
class car:
  def __init__(self,wheels,price):
    self.wheels = wheels
    self.price = price

class 자전차(car):
  def __init__(self,wheels,price):#상속받고 한번더 소환해서 오버라이딩한다 간단하게 말하면 car클래스에 선언받은걸 그대로 자전차에 들고와서 자전차 클래스로 덮어 쒸운다
    self.wheels = wheels
    self.price = price

cycle = car(2, 1000)
cycle.wheels,cycle.price
class car:
  def __init__(self,바퀴, 가격):
    self.바퀴 = 바퀴
    self.가격 = 가격

class 자동차(car):
    def __init__(self, 바퀴, 가격,):
        super().__init__(바퀴, 가격)#위에서 상속받은 car클래스에서 __init__메소드를 가져온다
        #차.__init__(self, 바퀴, 가격)
    def 정보(self):
        print("바퀴수 ",self.바퀴)
        print("가격 ",self.가격)
        

Car = 자동차(4,1000)
Car.정보()
class car:
  def __init__(self,바퀴, 가격,구동계):
    self.바퀴 = 바퀴
    self.가격 = 가격
    self.구동계 = 구동계
class 자전차(car):
    def __init__(self, 바퀴, 가격,구동계):
        super().__init__(바퀴, 가격,구동계)#위에서 상속받은 car클래스에서 __init__메소드를 가져온다
        #차.__init__(self, 바퀴, 가격)
    def 정보(self):
        print("바퀴수 ",self.바퀴)
        print("가격 ",self.가격)
        
bicycle = 자전차(2, 100, "시마노")
bicycle.정보()

마지막 문제는 자식호출이다 위에서 계승은 받았지만 super로 메소드를 상속받지 않았기 때문에

profile
프로그래머 꿈나무

0개의 댓글