ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [2월 1주차-2/4]📌 파이썬: 함수, 모듈, 클래스 정리
    Why Not SW CAMP 5기/수업 기록 2025. 2. 4. 17:02

     

    파이썬은 코드의 재사용성과 유지보수성을 높이기 위해 함수, 모듈, 클래스를 활용합니다. 이를 통해 중복 코드를 방지하고 개발 생산성을 높일 수 있습니다. 이번 글에서는 각각의 개념과 사용법을 살펴보겠습니다.


    ✅ 1. 함수(Function)

    함수는 특정 작업을 수행하는 코드 블록입니다. 동일한 로직을 반복적으로 사용할 경우, 함수를 활용하면 코드 중복을 줄이고 유지보수를 쉽게 할 수 있습니다.

    📍 함수 예제

    '''
    전일 종가, 상한, 하한을 입력받아
    상한가와 하한가를 한 번에 계산하여 반환하는 함수
    (상한, 하한 값은 매일 변경될 수 있음)
    '''
    def cal_upper_lower(price, up, low):
        upper = price * (1 + (up / 100))
        lower = price * (1 - (low / 100))
        return upper, lower
    
    upper, lower = cal_upper_lower(2000, 20, 30)
    print(upper)  # 2400.0
    print(lower)  # 1400.0
    

    ✅ 2. 모듈(Module)

    모듈은 여러 함수와 변수를 하나의 파일로 저장하여 재사용이 가능하도록 하는 코드 단위입니다. 이를 통해 코드의 구조화 및 유지보수가 용이해집니다.

    📍 모듈 생성 예제 (module_test.py)

    # module_test.py
    def cal_upper(price):
        return price * 1.3
    
    def cal_lower(price):
        return price * 0.7
    
    author = 'rubi'
    

    📍 모듈 사용 예제 (module_use.py)

    # module_use.py
    import module_test
    
    upper = module_test.cal_upper(12000)
    lower = module_test.cal_lower(5000)
    
    print(module_test.author)  # rubi
    print(upper, lower)  # 15600.0 3500.0
    

    ✅ 3. 시간 다루기 (time 모듈 활용)

    파이썬의 time 모듈을 사용하면 현재 시간 확인 및 프로그램의 실행을 일시 정지할 수 있습니다.

    📍 현재 시간 출력

    import time
    
    print(time.ctime())  # 현재 시간 출력
    # 예시: 'Tue Feb  4 12:07:08 2025'
    
    current_time = time.ctime()
    print(current_time.split()[-1])  # 연도만 추출 (2025)
    

    📍 sleep() 함수로 실행 지연

    import time
    
    for i in range(10):
        print(i)
        time.sleep(1)  # 1초씩 멈추면서 출력
    

    ✅ 4. 다양한 모듈 import 방법

    import os
    print(os.listdir())  # 현재 디렉토리 파일 목록 출력
    
    from os import listdir
    print(listdir())
    
    import os as winos
    print(winos.listdir())  # 별칭 사용
    

    ✅ 5. 파이썬 내장 함수 정리

    파이썬은 다양한 내장 함수를 제공합니다.

    # 절댓값
    print(abs(-3))  # 3
    
    # 유니코드 값을 문자로 변환
    print(chr(97))  # 'a'
    
    # enumerate() 활용
    for i, stock in enumerate(['naver', 'kakao', 'lg']):
        print(i, stock)
    '''
    출력:
    0 naver
    1 kakao
    2 lg
    '''
    
    # 객체의 메모리 주소 반환
    a = 1
    print(id(a))
    
    # 리스트 변환
    print(list('python'))  # ['p', 'y', 't', 'h', 'o', 'n']
    
    # 최댓값/최솟값
    lst = [2, 8, 5]
    print(max(lst))  # 8
    print(min(lst))  # 2
    
    # 정렬
    print(sorted(lst))  # [2, 5, 8]
    print(sorted(lst, reverse=True))  # [8, 5, 2]
    

    ✅ 6. 클래스(Class)

    파이썬은 객체 지향 프로그래밍(OOP) 을 지원하며, 클래스를 활용하면 데이터와 기능을 하나로 묶어 객체를 생성할 수 있습니다.

    📍 클래스 구조

    class BusinessCard:
        def __init__(self, name, email, addr):
            self.name = name
            self.email = email
            self.addr = addr
            
        def print_info(self):
            print('---------------')
            print(f'이름: {self.name}')
            print(f'이메일: {self.email}')
            print(f'주소: {self.addr}')
            print('---------------')
    
    # 객체 생성
    member1 = BusinessCard('rubi', 'rubi@n.com', 'seoul')
    member1.print_info()
    

    ✅ 7. 클래스 변수와 인스턴스 변수

    클래스 변수는 모든 객체가 공유하고, 인스턴스 변수는 각 객체마다 따로 저장됩니다.

    class Account:
        num_account = 0  # 클래스 변수 (모든 객체가 공유)
    
        def __init__(self, name):
            self.name = name  # 인스턴스 변수 (객체마다 다름)
            Account.num_account += 1
    
    # 객체 생성
    kang = Account('kang')
    kim = Account('kim')
    
    # 클래스 변수 확인
    print(Account.num_account)  # 2
    print(kang.num_account)  # 2
    print(kim.num_account)  # 2
    

    ✅ 8. 클래스 상속 (Inheritance)

    부모 클래스의 기능을 자식 클래스에서 물려받아 사용할 수 있습니다.

    class ParentClass:
        def can(self):
            print('pc의 can')
    
    class ChildClass(ParentClass):  # ParentClass를 상속받음
        pass
    
    p = ParentClass()
    p.can()  # pc의 can
    
    c = ChildClass()
    c.can()  # pc의 can
    

     


    ✅ 9. 실습: 연락처 관리 프로그램

    기능

    1. 연락처 입력
    2. 연락처 출력
    3. 연락처 삭제(이름 기준)
    4. 종료 시 연락처를 파일(txt)로 저장
    class Contact:
        def __init__(self, name, phone_number, e_mail, address):
            self.name = name
            self.phone_number = phone_number
            self.e_mail = e_mail
            self.address = address
        
        def print_info(self):
            print('---------------')
            print(f'name: {self.name}')
            print(f'phone number: {self.phone_number}')
            print(f'e-mail: {self.e_mail}')
            print(f'address: {self.address}')
            print('---------------')
    
    def set_contact():
        name = input('name: ')
        phone_number = input('phone number: ')
        e_mail = input('e-mail: ')
        address = input('address: ')
        return Contact(name, phone_number, e_mail, address)
    
    def print_contact(contact_list):
        for contact in contact_list:
            contact.print_info()
    
    def delete_contact(contact_list, name):
        for i, contact in enumerate(contact_list):
            if contact.name == name:
                del contact_list[i]
                break
    
    def store_contact(contact_list):
        with open('db.txt', 'wt') as f:
            for contact in contact_list:
                f.write(f"{contact.name}\n{contact.phone_number}\n{contact.e_mail}\n{contact.address}\n")
    
    def load_contact(contact_list):
        try:
            with open('db.txt', 'rt') as f:
                lines = f.readlines()
                for i in range(0, len(lines), 4):
                    name = lines[i].strip()
                    phone_number = lines[i+1].strip()
                    e_mail = lines[i+2].strip()
                    address = lines[i+3].strip()
                    contact_list.append(Contact(name, phone_number, e_mail, address))
        except FileNotFoundError:
            pass
    
    def print_menu():
        print('1. input')
        print('2. print')
        print('3. delete')
        print('4. end')
        return int(input('choose the menu: '))
    
    def run():
        contact_list = []
        load_contact(contact_list)
        while True:
            menu = print_menu()
            if menu == 1:
                contact_list.append(set_contact())
            elif menu == 2:
                print_contact(contact_list)
            elif menu == 3:
                delete_contact(contact_list, input('Enter the name to delete: '))
            elif menu == 4:
                store_contact(contact_list)
                break
    
    if __name__ == '__main__':
        run()
    

    🟢 실행 예시

    1. input
    2. print
    3. delete
    4. end
    choose the menu: 1
    name: Alice
    phone number: 010-1234-5678
    e-mail: alice@email.com
    address: Seoul
    
    1. input
    2. print
    3. delete
    4. end
    choose the menu: 2
    ---------------
    name: Alice
    phone number: 010-1234-5678
    e-mail: alice@email.com
    address: Seoul
    ---------------
    

     

    📝 정리

    • 함수: 코드 중복을 줄이고 유지보수를 쉽게 할 수 있음.
    • 모듈: 여러 함수를 파일로 저장하여 코드 재사용성을 높일 수 있음.
    • 시간 처리 (time 모듈): 현재 시간 출력 및 실행 일시 정지 기능 제공.
    • 내장 함수 활용: abs(), max(), enumerate() 등 다양한 기본 기능 제공.
    • 클래스: 객체 지향 프로그래밍을 통해 데이터와 기능을 하나로 묶음.
    • 클래스 변수와 인스턴스 변수: 클래스 변수는 모든 객체가 공유하고, 인스턴스 변수는 개별 객체가 저장.
    • 클래스 상속: 부모 클래스의 기능을 자식 클래스에서 활용 가능.

     

     

Designed by Tistory.