OOP

suhan cho·2022년 12월 29일
0

OOP

  • 객체 : 실생활에서 일종의 물건 속성와 행동을 가짐

  • OOP는 이러한 객체 개념을 프로그램으로 표현

    • 속성 -> 변수
    • 행동 -> 함수
  • 클래스(붕어빵 틀) 인스턴스(붕어빵)

  • class명 함수명

    • snake_case : 띄어쓰기 부분에 '_'를 추가 함수, 변수
    • CamelCase : Class명
class SoccerPlayer(object) : 
	def __init__(self, name, position, back_number) :
    	self.name = name
        self.position = position
        self.back_number = back_number
  • '__'는 특수한 예약함수나 변수 그리고 함수명 변경으로 사용

상속

  • 부모클래스로 부터 속성과 Method를 물려받은 자식 클래스 생성
class Person(object):
	def __init__(self, name, age):
    	self.name = name
        self.age = age

class Korean(Person):
	pass
first_korean = Korean("Lim", 35)
  • super를 사용하여 부모객체 사용
class Employee(Person):
	def __init__(self, name, age, gender, salary):
    	super().__init__(name, age, gender)
        self,salary = salary
   
	def do_work(self) # 새 메서드 추가
    	print("일 파이팅)

다형성

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

Visibility overview

  • 객체의 정보를 볼 수 있는 레벨을 조절하는 것
  • 누구나 객체 안에 변수를 볼 필요가 없다.

Encapsulation

  • 캡슐화 또는 정보 은닉
  • 심판 클래스가 축구선수 클래스 가족 정보까지 알 필요가 없다

예시1

  • product 객체를 Inventory 객체에 추가
  • Inventory에는 오직 Product 객체만 들어감
  • Inventory에 Product가 몇개인지 확인이 필요
  • Inventory에 Product items는 직접 접근 불가
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 itme add")
        else:
        	raise ValueError("Invaild Item")
    
    def get_number_of_item(self):
    	return len(self.__items) 

	#__item으로는 접근 못하고 새로운 변수명 items로 접근 가능하도록 해준다
	@property
	def items(self):
    	return self.__items

decorate

First class objects

  • 일등함수 또는 일급객체
# 함수를 변수로 사용
def square(x):
	return x*x
f = square
f(5)
  • 변수나 데이터 구조에 할당이 가능한 객체
  • 파라미터로 전달이 가능 + 리턴 값으로 사용
profile
안녕하세요

0개의 댓글