객체 : 실생활에서 일종의 물건. 속성(Attribute)과 행동(Action)을 가짐
OOP에서 속성은 변수(variable), 행동은 함수(method)로 표현됨
틀이라고 할 수 있는 '클래스'과 실제 구현체인 '인스턴스'로 나뉨
Attribute 추가는 init_ , self와 함께!
init은 객체 초기화 예약 함수
class SoccerPlayer(object):
def __init__(self, name, position, back_number):
self.name = name
self.position = position
self.back_number = back_number
매직 메서드는 특수한 예약 함수나 변수 그리고 함수명 변경(맨글링)으로 사용
예) main , add , str , eq
class SoccerPlayer(object):
def __str__(self):
return "Hello, My name is %s. I play in %s in center " % \
(self.name, self.position)
jinhyun = SoccerPlayer("Jinhyun", "MF", 10)
print(jinhyun)
method(Action) 추가는 기존 함수와 같으나, 반드시 self를 추가해야만 class 함수로 인정됨
class SoccerPlayer(object):
def change_back_number(self, new_number):
print("선수의 등번호를 변경합니다 : From %d to %d" % \ (self.back_number, new_number))
self.back_number = new_number
self의 의미 : 생성된 인스턴스 자신
jinhyun = SoccerPlayer("Jinhyun", "MF", 10)
print("현재 선수의 등번호는 :", jinhyun.back_number)
jinhyun.change_back_number(5)
print("현재 선수의 등번호는 :", jinhyun.back_number)
부모클래스로 부터 속성과 Method를 물려받은 자식 클래스를 생성 하는 것
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
class Korean(Person):
pass
first_korean = Korean("Sungchul", 35)
print(first_korean.name)
>>> Sungchul
class Employee(Person): # 부모 클래스 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," 입니다.")
같은 이름 메소드의 내부 로직을 다르게 작성
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
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())
객체의 정보를 볼 수 있는 레벨을 조절하는 것
캡슐화 또는 정보 은닉 (Information Hiding)
class Product(object):
pass
class Inventory(object):
def __init__(self):
self.__items = [] #private 변수로 선언 (타 객체가 접근 못함)
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)
class Inventory(object):
def __init__(self):
self.__items = []
@property # property decorator 숨겨진 변수를 반환하게 해줌
def items(self):
return self.__items
my_inventory = Inventory()
my_inventory.add_new_item(Product())
my_inventory.add_new_item(Product())
print(my_inventory.get_number_of_items())
items = my_inventory.items # Property decorator로 함수를 변수처럼 호출
items.append(Product())
print(my_inventory.get_number_of_items())
일등함수 또는 일급 객체
def square(x):
return x * x
f = square #함수를 변수로 사용
f(5)
def print_msg(msg):
def printer():
print(msg)
printer()
print_msg("Hello, Python")
def print_msg(msg):
def printer():
print(msg)
return printer
another = print_msg("Hello, Python")
another()
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")
복잡한 클로져 함수를 간단하게!
def star(func):
def inner(*args, **kwargs):
print("*" * 30)
func(*args, **kwargs)
print("*" * 30)
return inner
@star
def printer(msg):
print(msg)
printer("Hello")