ai tech

ai tech 4일차

완달프 2021. 1. 21. 16:49

파이썬에 대한 전반적인 지식은 모두 쌓은 것 같다.

데코레이터 부분이 이해가 잘 안되는데 개인적으로 공부해 봐야겠다.


강의

# 객체지향 프로그래밍

클래스는 도면, 인스턴스는 도면으로 만들어낸 실체

 

# 클래스

파이썬 클래스 명은 카멜케이스로 작성한다.

attribute 추가는 __init__(객체 초기화 함수, 생성자), self와 함께 사용한다

class SoccerPlayer(object):
    def __init__(self, name, position, back_number):
        self.name = name
        self.position = position
        self.back_number = back_number

# 파이썬에서의 언더바 2개의 의미

__는 특수한 예약함수나 변수 그리고 함수명 변경(맨글링) 목적으로 사용한다.

예시로는 __main__, __add__, __str__, __eq__ 등이 있다.

class SoccerPlayer(object):
    def __str__(self):
        return "Hello, My name is %s. I play in %s in center " % \ (self.name, self.position)

jinhyun = SoccerPlayer("Jinhyun", "MF", 10)
print(jinhyun) # 출력할때 형식을 __str__에서 정의한 형식을 따른다.

 

# self

클래스에서 사용되는 self는 생성된 실제 인스턴스 자기 자신을 가리킨다.

 

# 객체지향특징

상속, 다형성, 가시성

 

# 상속

부모클래스로부터 속성과 메소드를 물려받은 자식 클래스를 생성하는 것

class Employee(Person):
    def __init__(self, name, age, gender, salary, hire_date)
        super().__init__(name, age, gender) # 이름과 나이, 성별은 부모 객체를 사용
        self.salary = salary
        self.hire_date = hire_date

    def do_work(self):
        print("열심히 일을 합니다.")

    def about_me(slef):
        super().about_me() # 부모 클래스 함수 사용

 

# 다형성

같은 이름의 메소드의 내부 로직을 다르게 작성

다이나믹 타이핑 특성으로 인해 파이썬에서는 같은 부모클래스의 상속에서 주로 발생하게 된다.

즉, 파이썬에서는 부모 메소드 이름을 덮어써서 자식에서의 메소드를 구현할 수 있다.

 

# 가시성, 캡슐화, 정보은닉

누구나 객체안의 모든 변수를 볼 필요가 없으므로 객체의 정보를 볼 수 있는 레벨을 조절하는 것이다.

클래스를 설계할때, 클래스 간 간섭/정보공유를 최소화 한다.

인터페이스만 공개하고 이 인터페이스로 다른 클래스에서 정보를 사용할 수 있도록 하는 것이다.

class Inventory(object):
    def __init__(self):
        # 이렇게 선언하면 private 변수로 선언되므로 다른 객체가 접근할 수 없다.
        self.__items = [] 
    # property decorator를 달아주면 숨겨진 변수를 반환 할 수 있도록 해준다.
    @property 
    def items(self):
        return self.__items

my_inventory = Inventory()
items = my_inventory.items

 

# First-class objects

일등함수 또는 일급객체

변수나 데이터 구조에 할당이 가능한 객체

파라미터로도 전달이 가능하고 리턴값으로도 사용 가능

파이썬의 함수는 일급함수이다.

즉, 함수가 파라미터나 리턴값으로 사용가능하다.

def square(x):
    return x*x

f = square # 함수를 변수처럼 사용가능
f(5)

 

# Inner function, 내재함수

함수 내에 또 다른 함수가 존재 할 수 있다.

def print_msg(msg):
    def printer():
        print(msg)
    printer()
    
print_msg("Hello, Python")

 

# closures, 클로저

def print_msg(msg):
    def print():
        print(msg)
    return printer # 함수가 리턴된다.

another = print_msg("Hello, Python")
another()

 

# 클로저 또 다른 예제

def tag_func(tag, text):
    text = text
    tag = tag
    
    def inner_func():
        return '<{0}>{1}<{0}>'.format(tag, text)
        
    return inner_func
    
h1_func = tag_func('title', "This is Python Class")
p_func = tag_func('p', "Data Academy")

# 위와 같이 하나의 함수를 비슷하지만 다른 기능을 하는 다른 이름의 함수로 만들 수 있다.
# 로직이 반환되었지만 기존에 입력된 파라미터들을 온전히 유지한다.

 

# 데코레이터 함수, decorator function

복잡한 클로저 함수를 간단하게 만들수 있도록 해준다.

def star(func):
    def inner(*args, **kwargs):
        print("*" * 30)
        func(*args, **kwargs)
        print("*" * 30)
    return inner
    
def percent(func):
    def inner(*args, **kwargs):
        print("*" * 30)
        func(*args, **kwargs)
        print("*" * 30)
    return inner

@star
def printer(msg): # 이 함수가 star 함수의 func가 된다.
    print(msg)
printer("Hello")

# 결과
#******************************
#Hello
#******************************

@star
@percent
def printer(msg): # 이 함수가 star, percent 함수의 func가 된다.
    print(msg)
printer("Hello")

# 결과
#******************************
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#Hello
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#******************************
def generate_power(exponent):
    def wrapper(f):
        def inner(*args):
            result = f(*args)
            return exponent ** result
        return inner
    return wrapper
@generate_power(2) # 2는 generate_power 함수의 인자가 된다.
def raise_two(n): # raise_two함수는 wrapper 함수의 인자 f가 된다.
    return n**2

# 모듈

파이썬은 대부분의 라이브러리가 이미 다른 사용자에 의해서 구현되어 있다.

어떤 대상의 부분 혹은 조각

프로그램에서는 작은 프로그램 조각들

모듈들을 모아서 하나의 큰 프로그램을 개발한다.

프로그램을 모듈화 시키면 다른 프로그램이 사용하기 쉽다.

 

# 패키지

모듈을 모아놓은 단위, 하나의 프로그램

 

# 모듈 구현

파이썬에서 모듈은 py파일 하나를 의미한다.

같은 폴더에 다른 py파일이 있다면 import 문을 이용해서 모듈을 호출 할 수 있다.

#fah_converter.py
def convert_c_to_f(celcius_value):
    return celcius_value * 9.0 / 5 + 32
# module_ex.py
import fah_converter
print("Enter a celsius value: ")
celsius = float(input())
fahrenheit = fah_converter.convert_c_to_f(celsius)
print("That's", fahrenheit, " degrees Fahrenheit")

# namespace

모듈을 호출할때는 범위를 정할 수 있다.

모듈 안에는 함수와 클래스를 정의할 수 있다.

필요한 내용만 불러올 수 있다.

# alias 설정하기
import fah_converter as hah
print(fah.convert_c_to_f(41.6))

# 모듈에서 특정 함수 또는 클래스만 호출하기
from fah_converter import convert_c_to_f
print(convert_c_to_f(41.6))

# 모듈에서 모든 함수 또는 클래스를 호출하기
from fah_converter import *
print(convert_c_to_f(41.6))

# built in modules

파이썬이 기본 제공하는 라이브러리

문자처리, 웹, 수학 등의 다양한 모듈이 제공된다.

import 문을 써서 바로 사용 할 수 있다.

# 난수
import random
print(random.randint(0,100))
print(random.random())

# 시간
import time
print(time.localtime())

# 웹
import urllib.request
response = urllib.request.urlopen("http://thetemlab.io")
print(response.read())

# 패키지

하나의 대형 프로젝트를 만드는 코드의 묶음

다양한 모듈들의 합, 폴더로 연결됨

__init__, __main__등 키워드 파일명이 사용됨

다양하나 오픈 소스들이 모두 패키지로 관리됨

 

각 모듈 폴더안에는 __init__.py 파일이 존재한다.(옛날에는 필수였지만 3.3부터는 필요가 없다.)

# __init__.py
__all__ = ["image", "sound", "stage"]
from . import image
from . import sound
from . import stage

# stage/__init__.py
__all__ = ["main", "sub"]
from . import main
from . import sub

# sound/__init__.py
__all__ = ["bgm", "echo"]
from . import bgm
from . import echo

# image/__init__.py
__all__ = ["character", "object_type"]
from . import character
from . import object_type

# __main__.py
from sound import echo
if __name__ == '__main__':
    print("Hello Game")
	print(echo.echo_play())

# package namespace

패키지 내에서 다른 폴더의 모듈을 부를때

from game.graphic.render import render_test # 절대참조
from .render import render_test # 현재 디렉토리 기준
from ..sound.echo import echo_test # 부모 디렉토리 기준

# 파이썬 가상환경 설정

프로젝트 진행 시 필요한 패키지만 설치하는 환경이다.

기본 인터프리터 뿐만 아니라 프로젝트 종류별로 패키지를 설치한다.

다양한 패키지 관리 도구를 사용한다.

 

# 패키지 관리 도구

virtualenv + pip : 가장 대표적인 가상환경 관리 도구 이다.

conda : 상용 가상환경도구, 설치의 용이성이 있으며 윈도우에서 장점이다.

 

# conda로 가상환경 만들기

conda create -n my_project python=3.9
conda activate my_project # 가상환경적용
conda deactivate # 가상환경해제
conda activate my_project # 가상환경적용
conda install matplotlib

# matplotlib

대표적인 파이썬 그래프 관리 패키지

엑셀과 같은 그래프들을 화면에 표시한다

다양한 데이터분석 도구들과 함께 사용된다

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

# tqdm

남은시간 측정 도구

from tqdm import tqdm
import time
for i in tqdm(range(100000)):
    if i % 1000 == 0:
        tiem.sleep(1)

 

'ai tech' 카테고리의 다른 글

ai tech 6일차  (0) 2021.01.25
ai tech 5일차  (0) 2021.01.22
ai tech 3일차  (0) 2021.01.20
ai tech 2일차  (0) 2021.01.19
ai tech 1일차  (0) 2021.01.18