AI 부트캠프 | Week 2-1) (#클래스, #모듈과 패키지, #함수 실습)

Gomcha ·2023년 8월 2일
0

FC AI 6기 부트캠프

목록 보기
2/13
post-thumbnail

0. 목차

  1. 클래스
  2. 모듈과 패키지
  3. 함수 중급

1. 클래스

01. 클래스와 객체

01-1) 클래스

  • 클래스
    : 객체를 만들기 위한 설계도
class 클래스 이름:
	def 메서드 이름(self):
        명령블록    
class Monster:
	def say(self):
    	print("나는 몬스터다.")
  • 클래스 만들기
class Monster:
    def say(self):
        print("나는 몬스터다!")
        
goblin = Monster()
goblin.say()

# 파이썬에서는 자료형도 클래스다
a=10
b="문자열객체"
c=True

print(type(a))
print(type(b))
print(type(c))

# b에 들어있는 매서드 
print(b.__dir__())

01-2) 객체

  • 객체
    : 설계또로부터 만들어낸 작품
class 클래스 이름:
	def 메서드 이름(self):
    	명령블록
  • 호출하기
    - 인스턴스 = 클래스이름()
인스턴스.메서드()

goblin = Monster()
goblin.say()

01-3) 예제1)

  • 클래스를 사용하는 이유
# 클래스를 사용하는 이유
chamlion1_name="이즈리얼"
chamlion1_health=700
chamlion1_attack=90

print(f"{chamlion1_name}님 소환사의 협곡에 오신것을 환영합니다.")

chamlion2_name="라신"
chamlion2_health=800
chamlion2_attack=95

print(f"{chamlion2_name}님 소환사의 협곡에 오신것을 환영합니다.")

chamlion3_name="야스오"
chamlion3_health=750
chamlion3_attack=92

print(f"{chamlion3_name}님 소환사의 협곡에 오신것을 환영합니다.")

def basic_attack(name, attack):
    print(f"{name} 기본공격 {attack}")

basic_attack(chamlion1_name, chamlion1_attack)
basic_attack(chamlion2_name, chamlion2_attack)
basic_attack(chamlion3_name, chamlion2_attack)

print("================클래스를 사용한 경우===============")

class Champion:
    def __init__(self, name, health, attack):
        self.name = name
        self.health=health
        self.attack=attack
        print(f"{name}님 소환사의 협곡에 오신것을 환영합니다.")
    def basic_attack(self):
        print(f"{self.name} 기본공격 {self.attack}")
    
ezreal = Champion("이즈이얼",700,90)
leesin = Champion("리신",800,95)
yasuo = Champion("야스오",750,92)
ezreal.basic_attack()
leesin.basic_attack()
yasuo.basic_attack()

01-4) 예제2)

# Unit 클래스
class Unit:
    """_summary_
    속성 : 이름, 체력, 방어막, 공격력
    """
    # 생성자 (constructor)
    # 객체를 생성할 때 호출되는 매서드
    def __init__(self, name, hp, shield, damage):
        self.name=name # self는 객체 자기 자신을 의미
        self.hp=hp
        self.shield=shield
        self.damage=damage
        print(f"[{self.name}](이)가 생성 되었습니다.")
    
    # 객체를 출력할 때 호출되는 메서드
    def __str__(self):
        return f"[{self.name}] 체력 : {self.hp} 방어막 : {self.shield} 공격력 : {self. damage}"

# 프로브 객체를 생성
probe = Unit("프로브", 20, 20, 5)

# 질럿 객체를 생성
zealot = Unit("질럿", 100,60,16)

# 드라군 객체를 생성
dragoon = Unit("드라군", 100, 80, 20)

# 객체의 속성 정보를 출력
print(probe)
print(zealot)
print(dragoon)

01-5) 생성자

: 인스턴스를 만들 때 호출되는 메서드

class Monster:
    def __init__(self, health, attack, speed) :
        self.health = health
        self.attack = attack
        self.speed = speed
    def decrease_health(self, num):
        self.health -=num
    def get_health(self):
        return self.health    
# 고블린 인스턴스 생성
goblin=Monster(800,120,300)
goblin.decrease_health(100)
print(goblin.get_health())
# 늑대 인스턴스 생성
wolf=Monster(1500,200,350)
wolf.decrease_health(1000)
print(wolf.get_health())

01-6) 다양한 속성

  • 인스턴스 속성 : 객체마다 다른 값을 가지는 속성
    e.g.이름, 체력, 방어막, 공격력 등
  • 클래스 속성 : 모든 객체가 공유하는 속성
    e.g. 전체 유닛 개수
  • 비공개 속성 : 클래스 안에서만 사용가능한 속성
# 생성자 (constructor)
    # 객체를 생성할 때 호출되는 매서드
    count = 0
    def __init__(self, name, hp, shield, damage):
        self.name=name # self는 객체 자기 자신을 의미
        self.__hp=hp
        self.shield=shield
        self.damage=damage
        Unit.count += 1
        print(f"[{self.name}](이)가 생성 되었습니다.")
    
    # 객체를 출력할 때 호출되는 메서드
    def __str__(self):
        return f"[{self.name}] 체력 : {self.__hp} 방어막 : {self.shield} 공격력 : {self. damage}"

probe = Unit("프로브", 20, 20, 5)
zealot = Unit("질럿", 100,60,16)
dragoon = Unit("드라군", 100, 80, 20)

#인스턴스 속성 수정
probe.damage+=1
print(probe)

# 비공개 속성 접근
probe.__hp = 9999
print(probe)

# 네임 맹글링 (name mangling)
probe._Unit__hp = 9999
print(probe)

# 전체 유닛 개수
print(Unit.count)

01-7) 메서드

  • 인스턴스 메서드(instance method)
    : 인스턴스 속성에 접근할 수 있는 메서드
  • 클래스 메서드(class method)
    : 클래스 속성에 접근하는 메서드
# Unit 클래스
class Unit:
    """_summary_
    인스턴스 속성 : 이름, 체력, 방어막, 공격력
    클래스 속성 : 전체 유닛 개수
    
    """
    count = 0
    def __init__(self, name, hp, shield, damage):
        self.name=name 
        self.hp=hp
        self.shield=shield
        self.damage=damage
        Unit.count += 1
        print(f"[{self.name}](이)가 생성 되었습니다.")
    
    def __str__(self):
        return f"[{self.name}] 체력 : {self.hp} 방어막 : {self.shield} 공격력 : {self. damage}"

    # 인스턴스 메서드 (instance method)
    # 인스턴스 속성에 접근할 수 있는 메서드
    def hit(self, damage):
        # 방어막 변경 
        if self.shield >= damage:
            self.shield -= damage
            damage = 0
        else:
            damage -= self.shield
            self.shield = 0 
            
        # 체력 변경
        if damage >0 :
            if self.hp > damage:
                self.hp -= damage
            else:
                self.hp = 0

    # 클래스 메서드 (class method)
    # 클래스 속성에 접근하는 메서드
    @classmethod
    def print_count(cls):
        print(f"생성된 유닛 개수 : [{cls.count}] 개 ")    
probe = Unit("프로브", 20, 20, 5)
zealot = Unit("질럿", 100,60,16)
dragoon = Unit("드라군", 100, 80, 20)

probe.hit(16)
print(probe)
probe.hit(16)
print(probe)
probe.hit(16)
print(probe)

Unit.print_count()
  • 정적메서드(static method)
    : 인스턴스를 만들 필요가 없는 메서드
	@staticmethod
    def add(x, y):
        return x+y
    
    @staticmethod
    def sub(x, y):
        return x-y
    
print(Math.add(3,4))
print(Math.sub(3,4))

02.상속

02-1) 상속

: 클래스들에 중본된 코드를 제거하고 유지보수를 편하게 하기 위해서 사용

# 부모 클래스
class Monster:
    def __init__(self, name, health, attack) :
        self.name=name
        self.health=health
        self.attack=attack
    def move(self):
        print(f"[{self.name}] 지상에서 이동하기")
        
# 자식 클래스
class Wolf(Monster):
    pass

class Shark(Monster):
    def move(self): #메서드 오버라이딩
        print(f"[{self.name}] 헤엄치기")

class Dragon(Monster):
    def move(self): #메서드 오버라이딩
        print(f"[{self.name}] 날기")
        
wolf = Wolf("울프", 1500, 600)
wolf.move()

shark=Shark("샤크",3000,400)
shark.move()

dragon=Dragon("드래곤",8000,800)
dragon.move()

02-2) 예제1)

class Item:
    """
    속성 : 이름
    메서드 : 줍기, 버리기
    """
    def __init__(self, name):
        self.name=name
        
    def pick(self):
        print(f"[{self.name}]을(를) 주웠습니다.")
        
    def discard(self):
        print(f"[{self.name}]을(를) 버렸습닏.")
        
class Weapon(Item):
    """
    속성 : 공격력
    메서드 : 공격하기
    """
    def __init__(self, name, demage):
        super().__init__(name)
        self.demage=demage
    def attack(self):
        print(f"[{self.name}]을(를) 이용해 {self.demage}로 공격합니다.")

class HealingItem(Item):
    """
    속성 : 회복량
    메서드 : 사용하기
    """
    def __init__(self, name, recovery_amount):
        super().__init__(name)
        self.recovery_amount=recovery_amount
    def use(self):
        print(f"[{self.name}]을(를) 사용해 {self.recovery_amount}로 회복합니다.")
        
m16 = Weapon("m16", 110)
bungdae=HealingItem("붕대",20)

m16.attack()
bungdae.use()

02-3) 오버라이딩, 클래스

  • 클래스 변수
    : 인스턴스들이 모두 공유하는 변수
# 부모 클래스
class Monster:
    max_num = 1000
    def __init__(self, name, health, attack) : 
        self.name=name
        self.health=health
        self.attack=attack
        Monster.max_num -= 1
    def move(self):
        print(f"[{self.name}] 지상에서 이동하기")
        
# 자식 클래스
class Wolf(Monster):
    pass

class Shark(Monster):
    def move(self): #메서드 오버라이딩
        print(f"[{self.name}] 헤엄치기")

class Dragon(Monster):
    # 생성자 오버라이딩
    def __init__(self, name, health, attack):
        super().__init__(name,health, attack)
        self.skills = ("불뿜기", "꼬리치기", "날개치기")
    
    def move(self): #메서드 오버라이딩
        print(f"[{self.name}] 날기")
    
    def skill(self):
        print(f"[{self.name}] 스킬사용 {self.skills[random.randint(0,2)]}")

wolf = Wolf("울프", 1500, 600)
wolf.move()
print(wolf.max_num)

shark=Shark("샤크",3000,400)
shark.move()
print(shark.max_num)

dragon=Dragon("드래곤",8000,800)
dragon.move()
dragon.skill()
print(dragon.max_num)

02-4) 추상클래스

from abc import *


class Item(metaclass=ABCMeta):
    """
    속성 : 이름
    메서드 : 줍기, 버리기
    """
    def __init__(self, name):
        self.name=name
        
    def pick(self):
        print(f"[{self.name}]을(를) 주웠습니다.")
        
    def discard(self):
        print(f"[{self.name}]을(를) 버렸습니다.")
        
    @abstractmethod
    def use(self):
        pass
        
class Weapon(Item):
    """
    속성 : 공격력
    메서드 : 공격하기
    """
    def __init__(self, name, demage):
        super().__init__(name)
        self.demage=demage
    def use(self):
        print(f"[{self.name}]을(를) 이용해 {self.demage}로 공격합니다.")

class HealingItem(Item):
    """
    속성 : 회복량
    메서드 : 사용하기
    """
    def __init__(self, name, recovery_amount):
        super().__init__(name)
        self.recovery_amount=recovery_amount
    def use(self):
        print(f"[{self.name}]을(를) 사용해 {self.recovery_amount}로 회복합니다.")
        
m16 = Weapon("m16", 110)
bungdae=HealingItem("붕대",20)

m16.use()
bungdae.use()

03. 실습문제

01) 실습1)

# 클래스 생성

class Item:
    def __init__(self, name, price, weight, isdropable):
        self.name=name
        self.price=price
        self.weight=weight
        self.isdropable=isdropable
    
    def sale(self):
        print(f"[{self.name}] 판매가격은 [{self.price}]")
    
    def discard(self):
        if self.isdropable:
            print(f"[{self.name}] 버렸습니다.")
        else:
            print(f"[{self.name}] 버릴 수 없습니다.")

class WearbleItem(Item):
    def __init__(self, name, price, weight, isdropable, effect):
        super().__init__(name, price, weight, isdropable)
        self.effect=effect
    def wear(self):
        print(f"[{self.name}] 착용했습니다. {self.effect}")

class UsableItem(Item):
    def __init__(self, name, price, weight, isdropable, effect):
        super().__init__(name, price, weight, isdropable)
        self.effect=effect
    def use(self):
        print(f"[{self.name}] 사용했습니다. {self.effect}")
        
# 인스턴스 생성
sword = WearbleItem("이가닌자의 검", 30000,3.5,True, "체력 5000증가, 마력 5000증가")
sword.wear()
sword.sale()
sword.discard()

potion = UsableItem("신비한투명물약", 150000, 0.1, False, "투명효과 300초 지속")
potion.discard()
potion.sale()
potion.use()

02) 실습2)

# player 클래스 구현
# 1) 속성 : 닉네임, 미네랄, 가스, 유닛리스트


#유닛정보
unit_info = {"probe" : {
        "name":"프로브",
        "mineral" : 50,
        "gas": 0,
        "hp" : 20,
        "shield" : 20,
        "demage" : 5
    },
    "zealot" : {
        "name":"질럿",
        "mineral" : 100,
        "gas": 0,
        "hp" : 100,
        "shield" : 60,
        "demage" : 16
    },
    "dragon" : {
        "name":"드라군",
        "mineral" : 125,
        "gas": 50,
        "hp" : 100,
        "shield" : 80,
        "demage" : 20
    }
}

# 유닛 클래스
class Unit:
    """
    속성 : 이름, 체력, 방어막, 공격력
    """
    def __init__(self, name, hp, shield, demage):
        self.name=name
        self.hp=hp
        self.shiele=shield
        self.demage=demage

# 플레이어 클래스
class Player:
    """
    속성 : 닉네임, 미네랄, 가스, 유닛리스트
    메서드 : 유닛 생산하기
    """
    def __init__(self, nickname, mineral, gas, unit_list=[]):
        self.nickname=nickname
        self.mineral=mineral
        self.gas=gas
        self.unit_list=unit_list
    # 생산하기
    def produce(self, name, mineral, gas, hp, shield, demage):
        if self.mineral - mineral < 0:
            print("미네랄이 부족합니다.")
        elif self.gas-gas < 0:
            print("가스가 부족합니다.")
        else:
            self.mineral -= mineral
            self.gas -= gas
            unit = Unit(name, hp, shield, demage)
            self.unit_list.append(unit)
            print(f"[{self.name}]을(를) 생산합니다.")
            
#플래이어 생성
player1 = Player("Bisu", 400, 10)

# 유닛 생성
player1.produce(unit_info['probe']['name'], unit_info['probe']['mineral'], unit_info['probe']['gas'],
                unit_info['probe']['hp'], unit_info['dragon']['shield'],unit_info['dragon']['deamge'])
player1.produce(unit_info['dragon']['name'], unit_info['dragon']['mineral'], unit_info['dragon']['gas'],
                unit_info['dragon']['hp'], unit_info['zealot']['shield'],unit_info['zealot']['deamge']) 
player1.produce(unit_info['zealot']['name'], unit_info['zealot']['mineral'], unit_info['zealot']['gas'],
                unit_info['zealot']['hp'], unit_info['zealot']['shield'],unit_info['zealot']['deamge'])

2. 모듈과 패키지

01. 모듈

01-1) 내장모듈

: 파이썬 설치 시 자동으로 설치되는 모듈

import math
# from math import pi. ceil
print(math.pi)
print(math.ceil(2.7))

01-2) 외부모듈

: 다른 사람이 만든 파이썬 파일 pip로 설치해서 사용

import pyautogui as pg
pg.moveTo(500, 500, duration = 2)

02. 패키지

02-1)

02-2)

3. 함수중급

01.매개변수

01-1) 위치 매개변수

: 가장 기본적인 매개변수

def my_func(a, b):
    print(a, b)
    
my_func(2, 4)

01-2) 기본 매개변수

: 매개변수의 기본값을 지정할 수 있음

def post_info(title, content='내용없음'):
    print('제목 : ', title)
    print('내용 : ', content)
post_info("출석합니다.")

01-3) 키워드 매개변수

: 함수 호출 시에 키워드를 붙여서 호출(매개변수 순서를 지키지 않아도 됨)

def post_info(title, content):
    print("제목 : ", title)
    print("내용 : ", content)
post_info(content="없어요", title="남자친구 만드는 방법")

01-4) 위치 가변 매개변수

def print_fruits(*args):
    for arg in args:
        print(arg)

print_fruits('apple', 'orange', 'mango', 'grape')

01-5) 키워드 가변 매개변수

def comment_info(**kwargs):
    for key, value in kwargs.items():
        print(f'{key}:{value}')

comment_info(name='파린이', comment='정말 감사합니다!')

01-6) 매개변수 작성 순서

위치 - 기본 - 위치 가변 - 키워드(기본) - 키워드 가변

# 1. 방법
def post_info(title, content, *tags):
    print(f'제목 :', {title})
    print(f'내용 :', {content})
    print(f'태그 :', {tags})

post_info('파이썬 함수 정리!','다양한 매개변수 정리합니다.', '#파이썬', '#함수')

# 2. 방법
def post_info(*tags, title, content):
    print(f'제목 :', {title})
    print(f'내용 :', {content})
    print(f'태그 :', {tags})

post_info('#파이썬', '#함수',title='파이썬 함수 정리!',content='다양한 매개변수 정리합니다.')

02. 람다함수

02-1) 람다함수

: 이름이 필요없는 간단한 함수

# 기존 함수
def minus_one(a):
    return a-1

# 람다 함수 
lambda a : a-1
  • 호출방법 : 1. 함수 자체를 호출
print((lambda a : a-1)(10))
  • 호출방법 : 2. 변수에 담아서 호출
minus_one_2 = lambda a : a-1
print(minus_one_2(100))

02-2) if문 사용

람다함수에서 if문 사용

# 기존함수
def is_positive_number(a):
    if a>0:
        return True
    else:
        return False
    
#람다 함수
lambda a : True if a > 0 else False
  • 람다함수 호출방법 (1)
print((lambda a : True if a > 0 else False)(-2))
  • 람다함수 호출방법 (2)
is_positive_number = lambda a : True if a > 0 else False
print(is_positive_number(2))

03. map, filter함수

03-1) map함수

  • 사용이유
    : 기존 리스트를 수정해서 새로운 리스트를 만들 때
  • 사용방법
    : map(함수, 순서가 있는 자료형)
print(list(map(int, ['3','4','5','6'])))

03-2) 예제

  • 문제
    : 리스트 모든 요소의 공백 제거
items = [' 로지텍마우스 ', ' 앱솔키보드   ']
  • 1) for 사용
for i in range(len(items)):
    items[i] = items[i].strip()
print(items)
  • 2) map 사용
def strip_all(x):
    return x.strip()
items = list(map(strip_all, items))
print(items)
  • 3) 람다함수 사용
items = list(map(lambda x : x.strip(), items))
print(items)

03-3) filter함수

  • 사용이유
    : 기존 리스트에서 조건을 만족하는 요소만 뽑고 싶을 때
  • 사용방법
    : filter(함수, 순서가 있는 자료형)
def func(x):
    return x<0
print(list(filter(func, [-3, -2, 0, 5, 7])))

03-4) 예제

  • 문제
    : 리스트에서 길이가 3이하인 문자들만 필터링
animals=['cat', 'tiger','dog','bird','monkey']
  • 1) for 사용
result = []
for i in animals:
    if len(i) <= 3:
        result.append(i)
print(result)
  • 2) filter 사용
def word_check(x):
    return len(x) <= 3

result = list(filter(word_check, animals))
print(result)
  • 3) 람다함수 사용
result = list(filter(lambda x : len(x)<= 3, animals))
print(result)
profile
공부하는 데이터 분석가 👩‍💻

2개의 댓글

comment-user-thumbnail
2023년 8월 2일

이런 유용한 정보를 나눠주셔서 감사합니다.

1개의 답글