새소식

활동들/인프런 대학생 LEAF 2기

[인프런 리프 2기] 2. 파이썬 클래스 심화

  • -
728x90

2주차 미션: 섹션 2 ~ 3

 

생각해보면 클래스와 메소드를 각잡고 공부한 적은 없는 것 같다. 기본인데도 그냥 필요한 순간 찾아서 사용을 했다.

 

섹션 2를 통해 클래스와 메소드의 개념을 정리할 수 있었다.

코드와 그에 관한 필기를 주석으로 하나의 파일에 작성했다. (새로운 것 같다. 이런 식으로 해본 적은 없어서)

 

섹션 2에서 배운 내용은 다음과 같다.

 

  • 절차 지향 VS 객체 지향
  • 객체 지향 프로그래밍 장점
  • 클래스 기반 코딩 실습
  • 클래스 변수 VS 인스턴스 변수
  • 클래스 메도스 실습
  • 네임스페이스 이해
  • Class Method
  • Instance Method
  • Static Method
  • 3가지 메소드 활용 실습

 

아래는 강의 내용을 따라 작성한 섹션 2의 최종 코드이다.

# Chapter02
# 객체 지향 프로그래밍(OOP) -> 코드의 재사용, 코드 중복 방지, 유지보수, 대형프로젝트
# 규모가 큰 프로젝트(프로그램) -> 함주 중심 -> 데이터 방대 -> 복잡
# 클래스 중심 -> 데이터 중심 -> 객체로 관리

class Car():
  """
  Car class
  Author : Kim
  Date: 2021.03.22
  Description : Class, Static, Instance Method
  """

  # 클래스 변수(모든 인스턴스가 공유)
  price_per_raise = 1.0

  def __init__(self, company, details):
    self._company = company
    # self.car_count = 10
    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_calc(self):
    return 'After Car Price -> company : {}, price : {}'.format(self._company, self._details.get('price') * Car.price_per_raise)

  # Class Method
  @classmethod
  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
  def is_bmw(inst):
    if inst._company == 'Bmw':
      return 'OK! This car is {}'.format(inst._company)
    return 'Sorry. This car is not Bmw.'


#################################################################################

# self 의미
car1 = Car('Ferrari', {'color': 'White', 'horsePower': 400,'price': 8000})
car2 = Car('Bmw', {'color': 'Black', 'horsePower': 270,'price': 5000})

# 전체 정보
car1.detail_info()
car2.detail_info()

# 가격정보 (직접 접근) -> BUT 좋지 못한 방법 (캡슐화 문제)
print(car1._details.get('price'))
print(car1._details['price'])

# 가격정보(인상 전)
print(car1.get_price())
print(car2.get_price())

# 가격 인상(클래스 메소드 미사용)
Car.price_per_raise = 1.4

# 가격정보(인상 후)
print(car1.get_price_calc())
print(car2.get_price_calc())

# 가격 인상(클래스 메소드 사용)
Car.raise_price(1.6)

# 가격정보(인상 후)
print(car1.get_price_calc())
print(car2.get_price_calc())

# static method
# 인스턴스로 호출
print(car1.is_bmw(car1))
print(car2.is_bmw(car2))
# 클래스로 호출
print(Car.is_bmw(car1))

 

 

 

강의 링크:

우리를 위한 프로그래밍 : 파이썬 중급 (Inflearn Original)

 

우리를 위한 프로그래밍 : 파이썬 중급 (Inflearn Original) - 인프런 | 강의

본 강의는 파이썬 기초를 배운 학습자가 파이썬을 실무에 활용할 수 있도록 수준 높은 문법을 배우는 데 중점을 두고 있습니다. 파이썬만의 차별점을 파악하고 빠르게 익힘으로써 중급 레벨의

www.inflearn.com

 

728x90
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.