06 클래스

06 클래스

참고

애스크장고 AskDjango

파이썬은 객체지향언어이다.

OOP 주요 특징

  • Encapsulation (캡슐화): 관련 특성/기능을 하나의 클래스에 결합
  • Inheritance (상속): 코드 재활용성 증대
    • 부모 클래스의 특성/기능을 자식 클래스가 물려받음
    • 자식 클래스는 물려받은 특성/기능을 활용/변경/무시/재정의
  • Polymorphism (다형성): 다른 동작을 동일한 함수로 사용할 수 있도록 지원

클래스 정의

class 이름: 이름은 CamelCase 형태로 해준다.

  • snake_case: 소문자와 언더바(_)의 구성으로 함수에서 권장하는 형식
  • CamelCase: 단어를 이어 쓰며 대문자로 단어를 구분하는 형식, 클래스에 권장

클래스 사용 전

from math import sqrt

def get_area(circle):
    return circle['radius'] ** 2
def get_distance(circle1, circle2):
    return sqrt((circle1['x'] - circle2['x']) ** 2 + (circle1['y'] - circle2['y']) ** 2) \
    - (circle1['radius'] + circle2['radius']) # 코드를 다음줄로 이어가려면 '\'를 입력해 주자.

circle1 = {'x':10, 'y':20, 'radius':3}
circle2 = {'x':100, 'y':-40, 'radius':10}

get_area(circle1)
# 9

get_area(circle2)
# 100

get_distance(circle1, circle2)
# 95.16653826391968

가독성이 그리 좋지가 않다.

클래스 사용 후

from math import sqrt

class Circle:
    def __init__(self, x, y, radius):
        self.x = x
        self.y = y
        self.radius = radius
    def area(self):
        return self.radius ** 2
    def distance(self, other):
        return sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2) - (self.radius + other.radius)        

circle1 = Circle(10,20,3)
# 객체 생성 시에, 생성자 함수가 호출되며 인자가 전달
circle1.area() # 9

circle2 = Circle(100, -40, 10)
circle2.area() # 100

circle1.distance(circle2)
# self에는 자신이, other에는 circle2가 들어간다.
# 95.16653826391968

데이터와 함수를 클래스에 소속시킴으로써, 보다 깔끔하게 처리할 수 있다.

상속

상속에 대해 배워보자