GO WILD, SPEAK LOUD, THINK HARD

엘리스 AI 트랙 04주차 - 파이썬 객체지향 프로그래밍 (1/13) 🔥 본문

개발/엘리스 AI 트랙

엘리스 AI 트랙 04주차 - 파이썬 객체지향 프로그래밍 (1/13) 🔥

Max 2021. 1. 15. 21:31
반응형

✔ 04주차. 파이썬 프로그래밍

<수강 목표>

  • 프로그래밍에서 가장 많이 사용하는 함수를 효율적으로 작성하는 방법을 알아봅니다.

  • 객체지향 프로그래밍의 개념과 파이썬을 활용해 웹 사이트에서 정보를 가져오는 방법을 익힙니다.

  • 두개 이상의 모듈로 이루어진 패키지 단위의 프로그램을 작성할 수 있습니다.


[01 클래스 입문]

1. 이것이 클래스

  - 클래스 : 나타내고자 하는 개념의 설계도. (어떤 데이터가 있는지, 어떤 조작을 할 수 있는지, 어떤 제약조건들이 있는지 명시한 추상적인 설계도)

  - 인스턴스 : 클래스로 만든 실제 예시

class Post:
    # 속성
    author  = None
    comments = []
    likes = 0
    content = "What are you doing?"
    
    # 메소드
    def like(self, user):
    	self.likes += 1
        user.liked_posts.append(self)

2. 클래스 하나씩 따라하기

  - 생성자 : 모든 클래스의 가장 기본이 되는 메소드. 인스턴스가 처음 만들어질 때 어떻게 세팅할 것인지 결정

class Post:
    # 생성자
    def __init__(self, author, content):
    	self.author = author  # self : 클래스 내부의 속성/메소드에 접근할때 사용
        self.content = content

  - 속성을 만들 때 주의할 점 : 같은 내용을 나타내는 속성이 겹치면 안됨

# 잘못된 예
class Post:
    def __init__(self, author, content):
    	self.likes = 0
        self.liked_users = []

my_post = Post("elice", "Hello World!")
my_post.likes += 1  # likes 만 1이 올라가고 liked_users 는 비어있음 = 모순임

# 바른 예
class Post:
    def like(self, user):
        self.liked_users.append(user)

    def num_likes(self):
    	return len(self.liked_users)

 

3. 클래스 다듬기

  - 원하지 않는 값 배제하기

# 잘못된 예
class Post:
    def __init__(self, author, content):
        self.author = author
        self.content = content

    def like(self, user):
        self.liked_users.append(user)

    def num_likes(self):
    	return len(self.liked_users)

my_post = Post("elice", 1111)
my_post.like(["Hello", "World"])  # user 인스턴스가 들어가야 하는데 잘못된 값 들어갔음

# 바른 예
class Post:
    def __init__(self, author, content):
        if not isinstance(author, User):
        	return
        self.author = author
        
        if type(content) is not str:
        	return
        self.content = content
        ...

[02 클래스의 상속과 다형성]

1. 클래스의 상속

  - 상속이 필요한 이유 : 여러 클래스가 비슷한 속성과 메소드를 공유해야 할 때, 서로 다른 클래스 간의 계층 구조가 확실할 때 사용

# 게시물 클래스
class Post:
    def __init__(self, content):
        self.content = content

# (상속이 없다면) 이미지가 있는 게시물
class ImagePost:
    def __init__(self, content, images):
        self.content = content
        self.images = images

    def num_images(self):
        return len(self.images)

  - 클래스의 상속 : 자식 클래스는 부모 클래스의 속성 + 부모 클래스의 메소드 + 자기자신의 속성 + 자기자신의 메소드를 사용할 수 있다.

    → 청출어람의 법칙 : 부모 클래스보다 자식 클래스가 더 많은 데이터와 기능을 갖고 있다.

 

2. 상속 따라하기

  - 클래스 선언

# 클래스 선언
class ImagePost(Post):  # Post 클래스를 상속받은 ImagePost 클래스
    def __init__(self, content, images):
        super().__init__(content) # super : 부모 클래스에 접근할 때 사용
                                  # __init__ : 부모 클래스의 init 메소드를 불러옴 
                                  #  → 자식을 생성하면 연결되는 부모 인스턴스도 생성
        self.images = images

    def num_images(self):
        return len(self.images)

  - 속성상속

# 부모 클래스
class Post:
    def __init__(self, content):
        self.content = content
        self.likers = []

# 자식 클래스
class ImagePost(Post):
    ...

my_post = ImagePost(elice, "테스트")
print(my_post.likers)  # 부모클래스인 Post 의 속성인 likers 를 가져올 수 있음

  - 메소드 상속

# 부모 클래스
class Post:
    def like(self, user):
        self.likers.append(user)

# 자식 클래스
class ImagePost(Post):
    ...

my_post = ImagePost(elice, "테스트")
my_post.like(alice)  # 부모클래스인 Post 의 메소드인 like() 를 가져올 수 있음

  - 추상적인 부모 클래스

# 기존 클래스
class Like:
    def __init__(self, post, user):
        self.post = post
        self.user = user

class Sad:
    def __init__(self, post, user):
        self.post = post
        self.user = user

# 추상적인 부모 클래스를 적용
class Reaction:
    def __init__(self, type, post, user):
        self.type = type
        self.post = post
        self.user = user

class Like(Reaction):
    def __init__(self, post, user):
        super().__init__("LIKE", post, user)

class Sad(Reaction):
    def __init__(self, post, user):
        super().__init__("SAD", post, user)

4. 오버라이딩

  - Override : 자식이 부모가 했던 일을 확장하거나, 부모가 하는 일을 하지 않고 자신만의 일을 하는 것

class Post:
    def comment(self, user, content):
        self.comments.append(Comment(user, content))

class ProtectedPost(Post):
    def comment(self, user, content):
        print("Can't comment on protected posts")

 

[03 모듈과 패키지]

1. 모듈과 패키지

  - 모듈 : 다른 코드에서 사용할 수 있도록 열어 놓은 코드

# 모듈 불러오기1
import string

print(string.digits) # 0123456789

# 모듈 불러오기2
fromg string import digits

print(digits) # 0123456789

  - 모든 코드는 모듈임

# posts.py
class Post:
	...

class ImagePost(Post):
	...

# timeline.py
from posts import Post, ImagePost

timeline.add(Post("Hello"))

  - 패키지 : 모듈을 모아놓은 폴더

# 모듈 전체 불러오기
import facebook.users

# 원하는 모듈만 골라서 가져오기
from facebook import media

# 모듈 안에 정확하게 필요한 클래스와 함수만 불러오기
from facebook.posts import Post, ImagePost

# 내 코드와 불러온 모듈이 중복 될 경우 as 사용
from facebook.posts import Post as FacebookPost, ImagePost

2. matplotlib

  - matplotlib : mat - math / plot - 점을 찍다, 그래프를 그리다 / lib - library(외부에서 가져올 수 있는 공개된 코드)

# matplotlib 는 보통 plt 로 줄임
import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4]
y = [3, 5, 8, 2, 5]

plt.bar(x, y, align="center")
plt.show()

  - bar()

# bar graph
import matplotlib.pyplot as plt

# 사용방법
plt.bar(위치, 높이)
plt.show()

x = range(5)
y = [5, 4, 3, 2, 1]

plt.bar(x, y)
plt.show()

  - xticks()

# xticks
import matplotlib.pyplot as plt

# 사용방법
pos = range(4)
years = [2017, 2018, 2019, 2020]
temper = [12, 16, 19, 22]

plt.bar(pos, temper)
plt.xticks(pos, years)

  - matplotlib에서 한글 표시하기

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

# 한글 텍스트를 넣으려면 한글을 지원하는 폰트로 교체해야함
font = fm.FontProperties(fname='./NanumBarunGothic.ttf')

x = range(5)
y = [10, 20, 30, 40, 50]
ticks = []
for i in x :
    ticks.append(f"테스트 {i + 1}번")

plt.bar(x, y)
plt.title('그래프', fontproperties=font)  # title() : 그래프의 제목 설정
plt.xticks(x, ticks, fontproperties=font, rotation="vertical")  # rotation : 글자방향조절

  - 꺾은선 그래프 그리기

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

# 한글 텍스트를 넣으려면 한글을 지원하는 폰트로 교체해야함
font = fm.FontProperties(fname='./NanumBarunGothic.ttf')

x = range(5)
y = [10, 20, 30, 40, 50]
ticks = []
for i in x :
    ticks.append(f"테스트 {i + 1}번")

# plot : 꺾은선 그래프 그릴 때 사용
plt.plot(x, y)
# scatter : 선없이 분포도만 볼 때 사용
plt.scatter(x, y)

# fontproperties=font : 한글 사용시 추가
plt.title('그래프', fontproperties=font)  # title() : 그래프의 제목 설정
plt.xticks(x, ticks, fontproperties=font, rotation="vertical")  # rotation : 글자방향조절

 


※ 수업 자료의 출처는 K-Digital Training x 엘리스 인공지능 서비스 개발 기획 1기 (elice.io/)입니다.

반응형
Comments