Search
Duplicate

Python Object Oriented Programming

생성일
2023/02/16 14:39
태그

Python Object Oriented Programming

객체지향 프로그래밍 개요

Object-Oriented Programming, OOP
객체 : 실생활에서 일종의 물건
속성(Attribute) 와 행동(Action) 을 가짐
OOP 는 이러한 객체 개념을 프로그램으로 표현
속성은 변수(Variable), 행동은 함수(Method) 로 표현됨
파이썬 역시 객체 지향 프로그램 언어
ex)
인공지능 축구 프로그램을 작성한다고 가정
객체 종류 : 팀, 선수, 심판, 공
Action
선수 - 공을 차다, 패스하다
심판 - 휘슬을 불다, 경고를 주다
Attribute
선수 - 선수 이름, 포지션, 소속팀
팀 - 팀 이름, 팀 연고지, 팀소속 선수
OOP 는 설계도에 해당하는 클래스(class) 와 실제 구현체인 인스턴스(instance) 로 나눈다
Class - 붕어빵틀
인스턴스 - 붕어빵

Objects in Python

파이썬 naming rule

ex) CamelCase ⇒ 파이썬 Class 명에 사용
ex) snake_case ⇒ 파이썬 함수/변수명에 사용

Attribute 추가하기

Attribute(속성) 추가는 __ init __ , self 와 함께
__ init __ 은 객체 초기화 예약함수
# 축구 선수 정보를 class로 구현하기 class SoccerPlayer(object): # 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): print("Player Back Number Change!! : From %d to %d" % (self.back_number, new_number)) self.back_number = new_number
Python
복사

__ 의미

__ 는 특수한 예약 함수나 변수 그리고 함수명 변경(맨글링)으로 사용
ex) __ main __ , __ add __ , __ str __ , __eq __

method 구현하기

method(Action) 추가는 기존 함수와 같으나, 반드시 self 를 추가해야만 class 함수로 인정된다
self → 생성된 인스턴스 (클래스 안에서는)
abc.change_back_number(9) print(abc) park.back_number = 7 print(park)
Python
복사

OOP Implementation Example

구현가능한 OOP 만들기 - 노트북
# 클래스 Note class Note(object): def __init__(self, content = None): self.content = content def write_content(self, content): self.content = content def remove_all(self): self.content = "" def __add__(self, other): return self.content + other.content def __str__(self): return self.content # 클래스 NoteBook class NoteBook(object): def __init__(self, title): self.title = title self.page_number = 1 self.notes = {} def add_note(self, note, page = 0): if self.page_number < 300: if page == 0: self.notes[self.page_number] = note self.page_number += 1 else: self.notes = {page : note} self.page_number += 1 else: print("Page가 모두 채워졌습니다.") def remove_note(self, page_number): if page_number in self.notes.keys(): return self.notes.pop(page_number) else: print("해당 페이지는 존재하지 않습니다.") def get_number_of_pages(self): return len(self.notes.keys())
Python
복사

상속 (Inheritance)

부모 클래스로 부터 속성과 메소드를 물려받은 자식 클래스를 생성하는 것
super().__init__. → 부모 객체 init 불러온다
class Person(object): def __init__(self, name, age): self.name = name self.age = age def __str__(self): return "My name is {0}! Age is {1}!".format( self.name, self.age ) class Korean(Person): # 상속해준다 pass first_korean = Korean("ASH ISLAND", 22) print(first_korean) 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("Hard working..") def about_me(self): # 부모 클래스 함수 재정의 super().about_me() # 부모 클래스 함수 사용 print("My Salary is ", self.salary, "and, My Hire date is ", self.hire_date, ".")
Python
복사

다형성 (Polymorphism)

같은 이름 메소드의 내부 로직을 다르게 작성
Dynamic Typing 특성으로 인해 파이썬에서는 같은 부모클래스의 상속에서 주로 발생함
중요한 OOP의 개념 그러나 너무 깊게 알 필요 X
class Animal: def __init__(self, name): self.name = name def talk(self): # Abstract method, defined by convention only raise NotImplementedError("Subclass must implement abstrac method") class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): def talk(self): return 'Woof! Woof!' animals = [Cat('Missy'), Cat('Mr.Mistoffelees'), Dog('Lassie')] for animal in animals: print(animal.name + ': ' + animal.talk())
Python
복사

가시성 (Visibility)

객체의 정보를 볼 수 있는 레벨을 조절하는것
누구나 객체 안에 모든 변수를 볼 필요가 없음
객체를 사용하는 사용자가 임의로 정보 수정
필요 없는 정보에는 접근할 필요가 없음
만약 제품으로 판매한다면? 소스의 보호
self.__items ⇒ Private 변수로 선언, 타객체가 접근 못한다
@property : property decorator 숨겨진 변수를 반환하게 해줌
class Inventory(object): def __init__(self): self.__items = [] # no private self.test = "abc" 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) @property def items(self): return self.__items
Python
복사

decorate

First-class objects
일등함수 또는 일급객체
변수나 데이터 구조에 할당이 가능한 객체
파라미터로 전달이 가능 + 리턴값으로 사용
→ 파이썬의 함수는 일급함수
def square(x): return x * x f = square f(5)
Python
복사
Inner function
함수 내에 또 다른 함수가 존재
closures : inner function을 리턴값으로 반환
def print_msg(msg): def printer(): print(msg) printer() print_msg("Hello, Python")
Python
복사
def print_msg(msg): def printer(): print(msg) return printer another = print_msg("Hello, Python") another()
Python
복사
Decorator function
closure
# closure example 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")
Python
복사
복잡한 클로져 함수를 간단하게
decorator function
def generate_power(exponent): def wrapper(f): def inner(*args): result = f(*args) return exponent**result return inner return wrapper @generate_power(2) def raise_two(n): return n**2 print(raise_two(7))
Python
복사