ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Python Object Oriented Programming
    BoostCourse 2022. 12. 31. 01:53

    오늘은 BoostCourse에서 객체 지향 프로그래밍에 대해 배웠다.

    From TEAMLAB director 최성철

     

    특정 기능을 가지는 프로그램을 만들기 위해서, 시작부터 끝까지 순서대로 모든 기능을 구현하는 것은 비효율적일 수 있다.

    이때, 효율적으로 기능을 구현하기 위해서 OOP를 사용한다.

     

    먼저 OOP는 설계도에 해당하는 클래스와, 구현체인 인스턴스로 나눌 수 있다.

    설계도: 클래스(class), 붕어빵의 틀

    구현체: 인스턴스(instance), 붕어빵

    class SoccerPlayer(object):  
        def __init__(self, name, position, back_number):  
            self.name = name  
            self.position = position  
            self.back_number = back_number
    
        def change_back_number(self, new_number):
            pirnt("선수의 등번호를 변경합니다 : From %d to %d" % (self.back_number, new_number))
            self.back_number = new_number

    Soccer Player라는 클래스(설계도)를 만들었다.

    __init__은 객체 초기화 예약 함수

    name, position, back_number은 속성(Attribute)

    self.back_number = new_number은 행동(Action)

    Jisung = SoccerPlayer("Jisung", "MF", 11)
    Heungmin = ("Heungmin", "FW", 7)

    Jisung과 Heungmin이라는 인스턴스(구현체)를 만들었다.

    이제 Jisung.name, Jisung.position, Jisung.back_number를 활용할 수 있게 된다.


    한편, OOP는 Inheritance, Polymorphism, Visibility가 가능하다는 특징이 있다.

    1. Inheritance(상속)

    class Person(object):
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def about_me(self):
            print("저의 이름은 ", self.name, "이구요, 제 나이는 ", str(self.age), "살 입니다.")
    
    class Korean(Person):
        pass

    class Korean에서는 class Person과 동일한 메서드를 사용할 수 있게 된다.

    예를 들어 다음 코드를 실행하면 아래와 같은 실행 결과를 얻을 수 있다.

    Minwoo = Korean(Minwoo, 25)
    Minwoo.about_me()
    저의 이름은 Minwoo이구요, 제 나이는 25살 입니다.

    한편 super()를 사용해 부모 클래스의 속성과 메서드를 빌려올 수 있다.

    class Employee(Person):
        def __init__(self, name, age, salary):
            super().__init__(name, age)
            self.salary = salary
    
        def about_me(self):
            super().about_me()
            print("그리고 제 급여는 %d원 입니다." % (self.salary))

    2. Polymorphism(다형성)

    비슷한 동작을 수행하는 다양한 클래스에 같은 메서드 이름을 사용하되 내부 로직을 다르게 작성하는 방법이다.

    예를 들어, "울다"라는 동작을 수행하는 다양한 클래스(Dog, Cat, Chick)에 같은 메서드 이름 "Cry"를 사용하되 각각 개가 우는 소리, 고양이가 우는 소리, 병아리가 우는 소리를 출력하도록 코드를 짜는 것이다.

    class Animal(object):
        def __init__(self, name):
            self.name = name
    
        def Cry(self):
            raise NotImplementedError("Subclass must implement abstract method")

    raise NotImplementedError를 통해 자식 클래스에서 Cry 메서드를 구현해야 함을 명시하였다.

    class Dog(Animal):
        def Cry(self):
            print("월월")
    
    class Cat(Animal):
        def Cry(self):
            print("냐옹냐옹")
    
    class Chick(Animal):
        def Cry(self):
            print("삐약삐약")

    3. Visibility(가시성)

    객체의 정보를 볼 수 있는 수준을 조절하는 것

    class Product(object):
        pass
    
    class Inventory(object):
        def __init__(self):
            self.__items = []
    
        def add_new_item(self, product):
            if type(product) == Product:
                self.__items.append(product)
                print("new item added")
            else:
                raise ValueError("Invalid Item")
    
        def get_number_of_items(self):
            return len(self.__items)

    self.__items >>> Private 변수로 선언하여 타객체가 접근 못함

    이를 통해 self.items.append(str)로 직접적인 접근하는 것을 막아 프로그램의 목적에 맞지 않는 사용을 방지할 수 있다.


    ** 보너스 ** decorator

    첫째, 파이썬의 함수는 일급함수이므로 함수를 변수로 사용 가능하다.

    둘째, 함수 내에 또 다른 함수가 존재할 경우 inner function이라고 부른다.

    셋째, inner function을 return 값으로 반환할 경우 closures라고 부른다.

    def Hi(name):
        print("Hi")
        def Introduction():
            print("My name is %s" % (name))
        return Introduction

    Minwoo = Hi("Minwoo")

    Minwoo()

    >> Hi

    >> My name is Minwoo

     

    넷째, decorator를 활용하여 클로저 함수를 간단하게 구현할 수 있다.

    def Hi(func):
        def inner(*args, **kwargs):
            print("Hi")
            func(*args, **kwargs)
        return inner
    
    @Hi
    def Introduction(name):
        print("My name is", name)

    Introduction("Minwoo")

    >> Hi

    >> My name is Minwoo

    'BoostCourse' 카테고리의 다른 글

    벡터가 뭐에요?  (0) 2023.01.05
    Numpy  (1) 2023.01.05
    Exception/File/Log Handling  (0) 2023.01.02
    Module and Project  (0) 2023.01.02
    데이터 구조(Data Structure)  (0) 2022.12.29

    댓글

Designed by Tistory.