코드 내용
# chapter02_03 #
# 객체 지향 프로그래밍(OOP) -> 코드의 재사용, 코드 중복 방지 등
# 규모가 큰 프로젝트(프로그램) -> 함수 중심 -> 데이터 방대 -> 복잡
# 클래스 중심 -> 데이터 중심 -> 객체로서 관리
class Car():
"""
Car class
Author: Kim
Date:2020.04.05
Description : Class, Static, Instance Method
"""
#클래스 변수(모든 인스턴스가 공유)
price_per_raise = 1.0
def __init__(self, company, details):
self._company = company
self._details = details
def __str__(self):
return 'str : {} - {} '.format(self._company, self._details)
def __repr__(self):
return 'repr : {} - {} '.format(self._company, self._details)
# instance method
# self : 객체의 고유한 속성값
def detail_info(self):
print('Current ID: {}'.format(id(self)))
print('Car Detail info: {}, {}'.format(self._company, self._details.get('price')))
# instance method
def get_price(self):
return 'Before Car Price -> company: {}, price: {}'.format(self._company, self._details.get('price'))
# instance method
def get_price_culc(self):
return 'After Car Price -> company: {}, price: {}'.format(self._company, self._details.get('price') * Car.price_per_raise)
# class method
@classmethod # class method 구현 방법: @classmethod 키워드 이용, cls <- 클래스를 가리킴.
def raise_price(cls, per): # 클래스 메소드는 클래스 자체를 첫번째 인자로 넣어줘야 한다.
if per <= 1:
print('Please Enter 1 Or More')
return
cls.price_per_raise = per
print('Succeed! price increased')
# static method
@staticmethod # static method 구현 방법: @staticmethod 키워드 사용, inst <- 인스턴스를 가리킴.
def is_bmw(inst):
if inst._company == 'Bmw':
return 'OK! This car is {}'.format(inst._company)
else: return 'No!'
#self 의미
car1 = Car('Ferrari', {'color' :'White','horsepower':400, 'price':8000})
car2 = Car('Bmw', {'color' :'Black','horsepower':500, 'price':5000})
# 전체 정보
print(car1.detail_info)
print(car2.detail_info)
# 가격 정보 (직접 접근) // car1._details >> dict 형태로 반환이므로 get 메소드로 접근 가능
print(car1._details.get('price'))
print(car2._details['price'])
# 가격 정보 (인상 전)
print(car1.get_price())
print(car2.get_price())
# 가격 인상(클래스 메소드 미사용) 클래스 변수에 직접 접근함
Car.price_per_raise = 1.4
# 가격 정보 (인상 전)
print(car1.get_price_culc())
print(car2.get_price_culc())
# 가격 인상(클래스 메소드 사용) 클래스 메소드를 호출함
Car.raise_price(1.85)
# 가격 정보 (인상 후)
print(car1.get_price_culc())
print(car2.get_price_culc())
print()
print()
# static method // 인스턴스로 호출 // static method는 왜 존재하는거지? // instance를 입력값으로 받기 위해서라고 추측
print(car1.is_bmw(car1))
print(car1.is_bmw(car2))
# 클래스로 호출
print(Car.is_bmw(car1))
print(Car.is_bmw(car2))
# 정리하자면,
# class method -> class에 접근하기 위함
# member method -> instance의 변수들에 접근하기 위함
# static method -> ???
# ++ 추가로 알게 된 사실: class method는 cls를 첫 번째 입력으로 받고, static method는 받지 않는다.
# 상속과정에서 입력과정을 명확히 하고 싶다면, static method 보다 class method를 사용한다고 한다.
# 또한 class method나 instance method 둘다 애매한 상황에서, 유연하게 method를 만들고 싶으면
# instance method를 사용한다.
출력 결과
PS C:\Users\82107\Desktop\파이썬중급강의> ${env:DEBUGPY_LAUNCHER_PORT}='55756'; & 'C:\Users\82107\Anaconda3\python.exe' 'c:\Users\82107\.vscode\extensions\ms-python.python-2020.4.76186\pythonFiles\lib\python\debugpy\wheels\debugpy\launcher' 'c:\Users\82107\Desktop\파이썬중급강
의\p_study\chapter02_03.py'
<bound method Car.detail_info of repr : Ferrari - {'color': 'White', 'horsepower': 400, 'price': 8000} >
<bound method Car.detail_info of repr : Bmw - {'color': 'Black', 'horsepower': 500, 'price': 5000} >
8000
5000
Before Car Price -> company: Ferrari, price: 8000
Before Car Price -> company: Bmw, price: 5000
After Car Price -> company: Ferrari, price: 11200.0
After Car Price -> company: Bmw, price: 7000.0
Succeed! price increased
After Car Price -> company: Ferrari, price: 14800.0
After Car Price -> company: Bmw, price: 9250.0
No!
OK! This car is Bmw
No!
OK! This car is Bmw