Python with OOP

김예신·2022년 4월 4일

객체 지향 프로그래밍 (Object-Oriented Programming, OOP)


💡 기계적인 부품들을 조립해 제품을 만들 듯이 개발 할 때에도 객체들을 조립해 프로그램을 작성할 수 있도록 한 프로그래밍 기법

  • 장점
    1. 상속을 통한 재사용과 시스템의 확장이 용이
    2. 코드의 재활용성이 높음
    3. 자연적인 모델링에 의해 분석과 설계가 효율적
    4. 사용자와 개발자 사이의 이해력 높임
    5. 대형 프로그램의 작성이 용이
    6. 소프트웨어 개발 및 유지보수가 용이
  • 단점
    1. 프로그래밍 구현을 지원하는 정형화된 분석 및 설계 방법이 없음
    2. 구현 시 처리 시간이 지연됨



객체

💡 데이터(속성)와 이를 처리하기 위한 연산(메소드)를 결합시킨 실체
데이터 구조와 그 위에서 수행되는 연산들을 가지고 있는 모듈

  • 속성
    한 클래스 내에 속한 객체들이 가지고 있는 데이터 값을 단위별로 정의하는 것
    ex) 성질, 분류, 식별, 수량, 현재상태

  • 메소드
    객체가 메시지를 받아 실행해야 할 때 구체적인 연산을 정의하는 것
    객체의 상태를 참조하거나 변경하는 수단



객체지향 프로그래밍의 특징


캡슐화 (Encapsulation)

데이터(속성)와 데이터를 처리하는 함수를 하나로 묶는 것

캡슐화된 객체의 세부 내용은 외부에 은폐(정보 은닉)되어 변경이 발생할 때 오류의 파급 효과가 적다.
캡슐화된 객체는 재사용이 용이

  • 정보은닉
    다른 객체에게 자신의 정보를 숨기고 자신의 연산만을 통하여 접근을 허용하는 것 (캡슐화에 의해 이루어짐)
class Encap:
  def __init__(self,value):
  	self.value = value
  	print('init :', self.value)
    
  def _set(self):
  	print('set :', self.value)
    
  def printTest(self):
  	print('printTest :', self.value)

# object 생성
e = Encap(10)

# object 실행
e.__init__(20)
e._set()
e.printTest()


# result
>> init : 20
>> set : 20
>> printTest : 20



추상화 (Abstraction)

중요한 부분에 중점을 두어 개략화하는 것
불필요한 부분을 생략하고 객체의 속성 중 가장 중요한 것에만 중점을 두어 개략화 하는 것.(즉 모델화)

  • 추상화의 종류
    1. 과정추상화
    2. 데이터 추상화
    3. 제어 추상화
# 추상화 코드

from abc import *    # abc 모듈의 클래스와 메소드를 갖고온다.(abc : abstract base class)

# 추상 클래스
class People(metaclass=ABCMeta):  

# 추상 메소드
    @abstractmethod # 추상 메소드에는 @abstractmethod를 선언해줘야 함
    def charecter(self): 
        pass        # 추상 메소드는 기능 내 실제 실행내용은 없다.

# 상속받는 클래스
class Student(People):
    def charecter(self, pow, think):
        self.pow = pow
        self.think = think

        print('체력: {0}'.format(self.pow))
        print('생각: {0}'.format(self.think))

# 상속받는 클래스
class Driver(People):
    def charecter(self, pow, think):
        self.pow = pow
        self.think = think

        print('체력: {0}'.format(self.pow))
        print('생각: {0}'.format(self.think))

# Student object 생성      
peo1 = Student()
print('Student : ')

# Student object 실행
peo1.charecter(30, 10)

print()

# Driver object 생성
peo2 = Driver()
print('Driver : ')

# Driver object 실행
peo2.charecter(10, 10)

result

Student : 
체력: 30
생각: 10

Driver : 
체력: 10
생각: 10



상속성 (Inheritance)

상위 클래스의 속성을 하위 클래스가 물려받는 것
이미 정의된 부모 클래스의 모든 속성과 연산은 하위 클래스에서 동일하게 적용 됨

  • 상속성의 종류
    • 단일 상속 : 하나의 상위 클래스로부터 상속받는 것
    • 다중 상속 : 여러 개의 상위 클래스로부터 상속받는 것

Code

# 클래스 선언
class Person:
    def __init__(self, name):
        self.name = name
        
class Student(Person):      # Person 클래스 상속받음(name 변수를 파라미터로 재사용)
    def study(self):
        print (self.name + " studies hard")

class Employee(Person):     # Person 클래스 상속받음(name 변수를 파라미터로 재사용)
    def work(self):
        print (self.name + " works hard")

# object 생성
s = Student("Dave")
e = Employee("David")

# object 실행
s.study()
e.work()

result

Dave studies hard
David works hard

포함 Code

# 클래스 선언
class Person:
    def __init__(self, age):
        self.age = age

    def printPerson(self):          # 포함을 사용하기 위한 Person 클래스의 다른 함수
        print('Person_printPerson')

class Student:
    def __init__(self, age):
        self.age = age
        self.p = Person(self)       # Student가 Person에 포함되기 위해, Person 클래스에 대한 object 생성

    def aging(self):
        return self.age

    def personComposit(self,age):
        return age, self.p.printPerson()  # 포함개념적용된 Student 클래스의 Person object의 함수


# object 생성
s = Student(10) # 한 번 생성된 object는 파라미터가 변하지 않는 이상 출력값 또한 변하지 않는다.
p = Person(20)

# object 실행
print("s.aging() :", s.aging())   # result : 10


print('test')
print('print with test', "s.personComposit() :", s.personComposit(40)) 


print('test2')
print('print with test2', "p.printPerson() :", p.printPerson()) 

result

s.aging() : 10

test
Person_printPerson
print with test s.personComposit() : (40, None)

test2
Person_printPerson
print with test2 p.printPerson() : None



다형성 (Polymorphism)

객체가 가지고 있는 고유한 응답하는 능력
객체는 동일한 메소드명을 사용하며 같은 의미의 응답을 한다.

Code

class Person:
  def run(self):
    print('run')

  def play(self):
    print('play')
  
class Student(Person):
  def run(self):
    print('fast run')
  
  def play(self):
    print('play')
  
class teacher(Person):
  def teach(self):
    print('teach')

  def play(self):
    print('teach play')


# 리스트를 생성한다.
number = list()

# 생성한 리스트에 다형성 개념을 위해 다른 클래스(Student, teacher)가 상위 클래스(Person)를 참조할 수 있도록 한다.
number.append(Student())  # 리스트 끝에 서브 클래스 Student()를 넣습니다. 
number.append(teacher())  # 다시 리스트 끝에 서브 클래스 teacher()를 넣습니다.

print("=========")
for Student in number:
    Student.run()     # 상위클래스인 Person의 run은 상속하여 사용하지만 내용은 다르다.


print("=========")
for teacher in number: 
    teacher.play()    # 상위클래스인 Person의 play는 상속하여 사용하지만 내용은 다르다.

result

=========
fast run
run
=========
play
teach play



절차적 프로그래밍(PP, Procedural Programming) 과 비교

절차적 프로그래밍(PP)

Code

# 케이스 1 : 함수활용
def carAttribute():
  speed = 50
  color = 'black'
  model = 'CarModel'
  return speed,color,model


# 케이스 2 : 변수활용
speed = 20
color = 'yello'
model = 'AnotherCar'

print("Car Procedural Create Complete")
print("#Case 1 : Car Attribute ", carAttribute()) # return값을 통해 함수 요소값을 확인할 수 있다.
print("#Case 2 : Car Attribute ", speed,color,model) # 변수를 통해서만 값을 호출하므로, 소스코드가 증가한다.

result

Car Procedural Create Complete
#Case 1 : Car Attribute  (50, 'black', 'CarModel')
#Case 2 : Car Attribute  20 yello AnotherCar

객체지향 프로그래밍(OOP)

Code

# 아래와 같이 클래스 선언 순서에 관계없이 실행된다.
# 절차 프로그래밍과 다르게 기능별로 수행되기 때문이다.
class Bus:
  def __init__(self, speed, color):
      self.speed = speed
      self.color = color
  
  def drive_bus(self):
    self.speed = 70

class Car:
  def __init__(self, speed, color, model):
    self.speed = speed
    self.color = color
    self.model = model
  
  def drive(self):
    self.speed = 50


print("Car Speed by drive :", myCar.speed) # speed 변수에 값이 할당되지 않았기 때문에 0 출력
print("Bus Speed by drive :", myBus.speed)


#Car object method Call
myCar.drive()
myBus.drive_bus()
print("\ndriving speed")
print("Car Speed by drive :", myCar.speed) # 입출력순서에 상관없이 speed 개체를 변경하여 볼 수 있다.
print("Bus Speed by drive :", myBus.speed)

result

Car Speed by drive : 0 
Bus Speed by drive : 0

driving speed
Car Speed by drive : 50
Bus Speed by drive : 70

객체지향 프로그래밍 (OOP).pdf

profile
life is dancing

0개의 댓글