* python에서 반드시 알아야 할 OOP(Object-Oriented Programming) 개념에 대해서 종전보다 좀 더 깊게! 알아보자 😍
→ 실제 세상을 모델링
concepts>
* 객체 - 속성(attribute) & 행동(action) 두 개를 가짐 → OOP는 이러한 객체 개념을 프로그램으로 표현한다. 속성은 변수(variable), 행동은 함수(method)로 표현됨
* OOP는 설계도에 해당하는 class와 실제 구현체인 instance로 나눔
* __init__은 객체 초기화 예약 함수 + parameter로 여러 속성 정보 + self
★ __는 특수한 예약 함수나 변수 그리고 함수명 변경 맨글링(name mangling)으로 사용 - magic method
ex) __main__, __add__, __str__, __eq__
→ 'print 객체명'을 하면 __str__에서 선언된 return문이 나온다.
* method 추가는 기존 함수와 같으나, 반드시 self를 추가해야만 인정됨
* 예시 코드)
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):
print('선수의 등번호를 변경합니다: From %d to %d' % (self.back_number, new_number))
self.back_number = new_number
def __str__(self):
return "Hello, My name is %s. I play in %s in center" % \
(self.name, self.position)
def __add__(self, other):
return self.name + other.name
sehyun = SoccerPlayer("Sehyun", "MF", 10)
heungmin = SoccerPlayer("heungmin", "FW", 7)
print(sehyun) #Hello, My name is Sehyun. I play in MF in center
print(sehyun+heungmin) #Sehyunheungmin
inheritance>
* inheritance) 부모 클래스로부터 속성과 method를 물려받은 자식 클래스를 생성
→ super()는 부모 클래스를 뜻함
class Person:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
def about_me(self):
print('저의 이름은 ', self.name, '이구요, 제 나이는 ', str(self.age), '살 입니다.')
def __str__(self):
return '저의 이름은 ', self.name, '이구요, 제 나이는 ', str(self.age), '살 입니다.'
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('열심히 일을 합니다.')
def about_me(self):
super().about_me()
print('제 급여는 ', self.salary, '원 이구요, 제 입사일은 ', self.hire_date, ' 입니다.')
myPerson = Person('John', 34, 'Male')
myPerson.about_me()
#저의 이름은 John 이구요, 제 나이는 34 살 입니다.
myEmployee = Employee('Daeho', 34, 'Male', 300000, '2012/03/01')
myEmployee.about_me()
#저의 이름은 Daeho 이구요, 제 나이는 34 살 입니다.
#제 급여는 300000 원 이구요, 제 입사일은 2012/03/01 입니다.
* polymorphism>
→ 같은 이름 method의 내부 로직을 다르게 작성, 기능은 비슷하나 class가 다르다면 구현이 class별로 약간씩 다르다는 점
class Animal:
def __init__(self, name):
self.name = name
def talk(self):
raise NotImplementedError('Subclass must implement abstract 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())
#Missy: Meow!
#Mr. Mistoffelees: Meow!
#Lassie: Woof! Woof!
* visibility>
→ 객체의 정보를 볼 수 있는 레벨을 조절
→ 누구나 객체 안에 모든 변수를 볼 필요가 없음 (encapsulation)
→ 객체 변수 이름 앞에 __ 붙임 (property decorator로 숨겨진 변수 반환 가능)
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)
decorate>
* first-class objects>
→ 일급함수(일급 객체)로 변수나 데이터 구조에 할당이 가능한 객체, 파라미터로 전달이 가능 + 리턴 값으로 사용
→ 파이썬의 함수는 일급함수
def square(x):
return x*x
f = square
f(5) #함수를 변수로 사용
#--------------------------
def formula(method, argument_list): #함수를 파라미터로 사용
return [method(value) for value in argument_list]
* inner function>
→ 함수 내에 또 다른 함수가 존재
(closures: inner function 자체를 return값으로 반환)
def print_msg(msg):
def printer():
print(msg)
printer()
print_msg('Hello, Python')
#-------------------------------
#closures
def print_msg(msg):
def printer():
print(msg)
return printer
another = print_msg('hello, python')
another()
→ decorator function으로 복잡한 closure 함수를 간단하게 코드로 짤 수 있음!
(아래 예를 보면 @star- 즉, star 다음에 오는 함수 printer가 star()의 parameter func로 들어옴)
def star(func):
def inner(*args, **kwargs):
print('*' * 30)
func(*args, **kwargs)
print('*' * 30)
return inner
@star
def printer(msg):
print(msg)
printer('hello')
※ 즉 @으로 언급한 함수를, 일종의 꾸며주는 decorator 함수를 그 다음에 선언하는 것.
+ python decorator 추후 더 자세한 포스팅 참조! +
* 출처) Naver AI Tech pre-course
* magic method 참고자료) https://corikachu.github.io/articles/python/python-magic-method
'Python > Fundamentals' 카테고리의 다른 글
list, string, tuple, dictionary, set (iterables) (0) | 2022.08.19 |
---|---|
File/Exception/Log Handling (0) | 2022.07.14 |
Python Basics(2). (from Coursera) (0) | 2022.04.13 |
Python Basics(1). (from Coursera) (0) | 2022.04.04 |
시계열 데이터 - datetime (0) | 2022.03.24 |
댓글