본문 바로가기
BackEnd/파이썬

[파이썬] 파이썬으로 객체 지향 프로그래밍 구현

by whdgus928 2023. 1. 31.

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

 

객체: 실생활에서 일종의 물건, 속성과 행동을 가짐. OOP는 이러한 객체 개념을 속성은 변수, 행동은 함수로 표현

ex) 붕어빵 틀: class, 붕어빵: instance

 

※ 변수명 상식

- snake_case : 띄워쓰기 부분에 “_” 를 추가 뱀 처럼 늘여쓰기, 파이썬 함수/변수명에 사용

- CamelCase: 띄워쓰기 부분에 대문자 낙타의 등 모양, 파이썬 Class명에 사용

 

class 선언

class SoccerPlayer(object):

Attribute 추가하기

  - 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

※ __(언더바 두 개)는 특수한 예약 함수나 변수 그리고 함수명 변경(맨글링)으로 사용

ex) __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 구현하기

  - 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

objects(instance) 사용하기

jinhyun = SoccerPlayer("Jinhyun", "MF", 10)
print("현재 선수의 등번호는 :", jinhyun.back_number)
jinhyun.change_back_number(5)
print("현재 선수의 등번호는 :", jinhyun.back_number)

전체 구현하기

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

jinhyun = SoccerPlayer("Jinhyun", "MF", 10)
print("현재 선수의 등번호는 :", jinhyun.back_number)
jinhyun.change_back_number(5)
print("현재 선수의 등번호는 :", jinhyun.back_number)

 

객체 지향 언어 특징

상속: 부모클래스로부터 속성과 메소드를 물려받은 자식 클래스를 생성하는 것

class Person(object): # 부모 클래스 Person 선언
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
    def about_me(self): # Method 선언
    	print("저의 이름은 ", self.name, "이구요, 제 나이는 ", str(self.age), "살 입니다.")

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())

 

가시성: 누구나 객체 안에 모든 변수를 볼 필요가 없음. Private 변수로 선언해 타객체가 접근 못함

Private 지정하는 방법: self.__items = [] # 변수 앞에 언더바 두개 붙인다

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)

my_inventory = Inventory()
my_inventory.add_new_item(Product())
my_inventory.add_new_item(Product())
print(my_inventory.get_number_of_items())
print(my_inventory.__items)
my_inventory.add_new_item(object)

※ property:  decorator의 한 종류 숨겨진 변수를 반환하게 해줌

class Inventory(object):
    def __init__(self):
    	self.__items = []
    @property
    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
items.append(Product())
print(my_inventory.get_number_of_items())

 

※ 캡슐화: class를 설계할 때 클래스 간 간섭/ 정보공유의 초소화

 

decorate: 함수를 수정하지 않은 상태에서 추가 기능을 구현할 때 사용

class Student:
	def __init__(self, name, marks):
		self.name = name
		self.marks = marks
		# self.gotmarks = self.name + ' obtained ' + self.marks + ' marks'
	@property
	def gotmarks(self):
		return self.name + ' obtained ' + self.marks + ' marks'

 

 

자료 출처 

네이버 부스트코스

반응형

댓글