새소식

부스트캠프 AI Tech 4기

3. 객체지향 프로그래밍

  • -

Object-Oriented Programming : OOP

OOP는 설계도에 해당하는 class와 실제 구현체인 instance가 있다.

 

객체(object)는 클래스(class)의 instance이다. 즉, instance는 클래스에 속하는 객체라고 할 수 있다.

 

__는 특수한 예약 함수나 변수, 함수명 변경(맨글링)으로 사용할 수 있다.

ex. __main__, __add__, __str__

 

__str__의 사용 예시

class Player(object):
    def __init__(self, name:str):
        self.name = name
        
    def __str__(self):
        return f"Hello, My name is {self.name}"

player1 = Player("Kong")

print(player1)
# Hello, My name is Kong

 

method(Action)추가는 기존 함수와 같으나 반드시 self를 추가해야만 class 함수로 인정된다.

self는 생성된 instance 자기 자신을 의미한다.

 

OOP Characteristic

  • Inheritance : 상속
  • Polymorphism : 다형성
  • Visibility : 가시성

상속(inheritance)

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

다형성(Polymorphism)

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

가시성(Visibility)

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

class Inventory:
	def __init__(self):
    	self.__imtes = [] 
    
    def add_new_item(self, product):
    	self.__items.append(product)
    
    def get_number_of_items(self):
   		return len(self.__items)
     
    @property  # 숨겨진 변수 반환
    def items(self):
    	return self.__items
inven = Inventory()
inven.add_new_item(Product())

inven.__items 
# AttributeError: 'inven' object has no attribute '__items"

items = inven.items # property decorator로 함수를 변수처럼 호출

 

decorator 

개인적으로 데코레이터를 정리한 글

First-class objects

  • 변수나 데이터 구조에 할당이 가능한 객체
  • 파이썬의 모든 함수는 일급함수이다.
def square(x):
	return x * x

f = square
f(5)
# 25
  • 함수를 파라미터로도 사용이 가능하다.
def formula(method, arg_list):
	return [method(val) for val in arg_list]

inner function

  • 함수 내에 또 다른 함수가 존재
def print_msg(msg):
	def printer():
    	print(msg)
    printer()

print_msg("Hello inner function!")
# Hello inner function!
  • Closure : inner function을 return값으로 반환 (파이썬은 일급객체이기 때문)
    같은 이름으로 비슷한 다양한 목적의 function을 만들어 낼 수 있다.
def print_msg(msg):
    def printer():
        print(msg)
    return printer

closure = print_msg("Hello Closure")
closure()
# Hello Closure

decorator function

  • 복잡한 closure 함수를 간단하게 만들어준다.

printer 함수가 star함수의 func위치에 들어가게 된다.

def star(func):
    def inner(*args, **kwargs):
        print(args[1] * 30)
        func(*args, **kwargs)
        print(args[1] * 30)
    return inner

@star
def printer(msg, mark):
    print(msg)

printer("Hello decorator", "@")

printer("Hello @")
# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
# Hello decorator
# @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

 

 


부스트캠프 AI Tech 교육 자료를 참고하였습니다.

728x90

'부스트캠프 AI Tech 4기' 카테고리의 다른 글

5. Python data handling  (0) 2022.09.23
5. Numpy  (0) 2022.09.23
4. Module and Project/가상환경  (2) 2022.09.21
2. Data Structure/Pythonic Code  (0) 2022.09.18
1. Variables/String & Advanced function concept  (0) 2022.09.16
Contents