λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

Python/Python

[Python 쀑급] Class와 Method 심화

λ°˜μ‘ν˜•

πŸ”Š ν•΄λ‹Ή ν¬μŠ€νŒ…μ€ μΈν”„λŸ°μ˜ 파이썬 쀑급 κ°•μ˜λ₯Ό κ³΅λΆ€ν•˜λ©΄μ„œ λ³΅μŠ΅μ°¨μ›μœΌλ‘œ μ •λ¦¬ν•œ ν¬μŠ€νŒ…μž…λ‹ˆλ‹€. ν•΄λ‹Ή λ‚΄μš©μ€ 주둜 본인의 λ³΅μŠ΅μš©μ΄λΌμ„œ μžμ„Έν•œ μ„€λͺ…은 μ—†λŠ” 점 μ–‘ν•΄ λΆ€νƒλ“œλ¦¬κ² μŠ΅λ‹ˆλ‹€. 원본 μ½”λ“œλŠ” 여기에 μžˆμŠ΅λ‹ˆλ‹€.

 

Python

 

객체 지ν–₯ ν”„λ‘œκ·Έλž˜λ°(OOP)λŠ” μ½”λ“œμ˜ μž¬μ‚¬μš©κ³Ό μ½”λ“œ 쀑볡을 λ°©μ§€ν•˜κΈ° μœ„ν•œ ν”„λ‘œκ·Έλž˜λ° 방법이닀. 이번 ν¬μŠ€νŒ…μ—μ„œ Python ν΄λž˜μŠ€μ™€ λ©”μ„œλ“œμ— λŒ€ν•œ μ‚¬μš©λ²•μ— λŒ€ν•΄ μ˜ˆμ‹œ μ½”λ“œλ‘œ μ•Œμ•„λ³΄μž.

 

class Car(object):
    def __init__(self, company, detail):
        self._company = company
        self._detail = detail
    # Python에 λ‚΄μž₯λ˜μ–΄ μžˆλŠ” λ©”μ†Œλ“œλ₯Ό ν™œμš©ν•΄μ„œ μΈμŠ€ν„΄μŠ€μ— μžˆλŠ” 정보 좜λ ₯ κ°€λŠ₯
    # __str__은 μ‚¬μš©μž μž…μž₯μ—μ„œ μ‚¬μš©ν•˜λŠ” 좜λ ₯ λ©”μ„œλ“œ
    def __str__(self):
        return f"{self._company}: {self._detail}"
    # __repr__ (representation)은 개발자 μž…μž₯μ—μ„œ μ‚¬μš©ν•˜λŠ” 좜λ ₯ λ©”μ„œλ“œ
    def __repr__(self):
        return f"{self._company}: {self._detail}"

 

  • __init__ 은 μƒμ„±μž ν•¨μˆ˜λ‘œ μΈμŠ€ν„΄μŠ€ λ©”μ„œλ“œ μ‚¬μ΄μ—μ„œ 일반적으둜 κ³΅μœ κ°€ κ°€λŠ₯ν•œ λ³€μˆ˜λ“€μ„ μ •μ˜
  • __str__, __repr__ 은 Python에 기본적으둜 λ‚΄μž₯λ˜μ–΄ μžˆλŠ”(built-in) 메직 λ©”μ„œλ“œλ‘œ 두 λ©”μ„œλ“œμ˜ 역할은 λΉ„μŠ·ν•˜μ§€λ§Œ 주석에 λ³΄μ΄λŠ” 것과 같이 μ‚¬μš©μž level, 개발자 levelμ—μ„œ 각각 μ‚¬μš©λœλ‹€κ³  함(μ‚¬μš©μž level, 개발자 levelμ΄λž€ 단어에 λŒ€ν•΄μ„œ 아직 μ²΄κ°λ˜μ§€ μ•ŠμŒ..) 메직 λ©”μ„œλ“œμ— λŒ€ν•΄μ„œλŠ” λ‹€μŒ ν¬μŠ€νŒ…μ—μ„œ 더 μžμ„Ένžˆ λ‹€λ£Έ.
class Car(object):
    # Docstring => Class.__doc__으둜 ν΄λž˜μŠ€μ— λŒ€ν•œ μ„€λͺ… 정보 좜λ ₯ κ°€λŠ₯!
    """
    Car Class : μžλ™μ°¨ 클래슀
    Author : Jo
    Datetime : 2020-12-19
    """
    # 클래슀 λ³€μˆ˜ μ •μ˜
    car_count = 0

    def __init__(self, company, detail):
        self._company = company
        self._detail = detail
        # self.car_count = 100
        # 클래슀 λ³€μˆ˜ μ΄μš©ν•˜κΈ°
        Car.car_count += 1

    def __str__(self):
        return "{} - {}".format(self._company, self._detail)

    def __repr__(self):
        return '{} - {}'.format(self._company, self._detail)

    # del λ©”μ†Œλ“œ μƒμ„±ν•΄μ„œ 클래슀 λ³€μˆ˜ κ°μ†Œμ‹œμΌœλ³΄κΈ°
    def __del__(self):
        Car.car_count -= 1

    def detail_info(self):
        print("Current ID :", id(self))
        print("Detail info: ", self._detail.get('price'))

 

  • Doctstring 으둜 λ˜μ–΄μžˆλŠ” """ ~ """ 주석 뢀뢄은 μ •μ˜ν•œ ν΄λž˜μŠ€μ— λŒ€ν•œ μ„€λͺ…을 μž‘μ„±ν•˜λŠ” κ³³. μ‹ κΈ°ν•˜κ²Œλ„ __doc__ 맀직 λ©”μ„œλ“œλ‘œ 호좜이 κ°€λŠ₯함. 
  • car_count : 클래슀 μ•ˆμ΄μ§€λ§Œ μΈμŠ€ν„΄μŠ€ λ©”μ„œλ“œ λ°–μ—μ„œ μ •μ˜ν•˜λŠ” '클래슀 λ³€μˆ˜'둜 클래슀 μ•ˆμ—μ„œ μ •μ˜λ˜λŠ” λͺ¨λ“  μΈμŠ€ν„΄μŠ€ λ©”μ„œλ“œλ“€ λͺ¨λ‘ κ³΅μœ κ°€ κ°€λŠ₯함. 즉 μΈμ„œν„΄μŠ€ λ©”μ„œλ“œ μ•ˆμ—μ„œ 'Class_name.class_variable' μ‹μœΌλ‘œ 호좜이 κ°€λŠ₯
  • detail_info : 기본적인 μΈμŠ€ν„΄μŠ€ λ©”μ„œλ“œμž„. 이λ₯Ό 톡해 μƒμ„±μž ν•¨μˆ˜μ•ˆμ—μ„œ μ •μ˜λœ λ³€μˆ˜λ₯Ό μ‚¬μš©ν•˜κ±°λ‚˜ μΈμŠ€ν„΄μŠ€ λ©”μ„œλ“œμ— μΆ”κ°€ νŒŒλΌλ―Έν„°λ₯Ό 집어 넣을 수 있음

λ‹€μŒμ€ 클래슀 λ©”μ†Œλ“œ, μΈμŠ€ν„΄μŠ€ λ©”μ†Œλ“œ, Static λ©”μ†Œλ“œμ— λŒ€ν•΄μ„œ μ•Œμ•„λ³΄μž.

 

class Car():
    # 클래슀 λ³€μˆ˜ μ •μ˜
    price_per_raise = 1.0

    def __init__(self, company, detail):
        self._company = company
        self._detail = detail

    def __str__(self):
        return f"{self._company} - {self._detail}"

    # μΈμŠ€ν„΄μŠ€ λ©”μ†Œλ“œ - 가격 상ν–₯ μ „
    def detail_info(self):
        #print(id(self))
        print(f"Company:{self._company} - Price:{self._detail.get('price')}")
        return
    # μΈμŠ€ν„΄μŠ€ λ©”μ†Œλ“œ - 가격 상ν–₯ ν›„
    def detail_info_after(self):
        print(f"Company:{self._company} - Price:{self._detail.get('price') * Car.price_per_raise}")
        return

    # 클래슀 λ©”μ†Œλ“œ : 클래슀 λ³€μˆ˜λ₯Ό μ‘°μž‘ν•˜κ³  μ΄μš©ν•˜κΈ° μœ„ν•œ λ©”μ†Œλ“œ
    # cls = Car 클래슀λ₯Ό λ‚˜νƒ€λ‚Έλ‹€κ³  μƒκ°ν•˜λ©΄ 됨!
    @classmethod
    def raise_price(cls, per):
        if per <= 1.0:
            print("Please enter 1 or more.")
            return
        cls.price_per_raise = per
        return "Success! Price is increased!"

    # Static λ©”μ†Œλ“œ : 클래슀 λ³€μˆ˜λ₯Ό μ΄μš©ν•˜μ§„ μ•Šμ§€λ§Œ μœ λ™μ μœΌλ‘œ μ‚¬μš©ν•˜κ³  싢을 λ•Œ! Static λ©”μ†Œλ“œλŠ” cls, self같은 νŒŒλΌλ―Έν„° 받지 μ•ŠμŒ!
    # ex. μ–΄λ–€ μ°¨κ°€ ν˜„λŒ€ 차인지 μ•Œμ•„λ³΄κΈ° μœ„ν•œ λ©”μ†Œλ“œ μ •μ˜!
    @staticmethod
    def is_hyundai(instance):
        if instance._company == 'Hyundai':
            return "This car is a kind of Hyundai cars."
        return "This is not a kind of Hyundai cars."

car1 = Car('Hyundai', {'color': 'white', 'horsepower': 400, 'price': 8000})
car2 = Car('Samsung', {'color':'black','horsepower': 500,'price': 5000})

print("Before")
car1.detail_info()
car2.detail_info()
# 가격 μƒμŠΉμ‹œν‚€λŠ” 클래슀 λ©”μ†Œλ“œ 호좜!
Car.raise_price(1.5)
print("After")
car1.detail_info_after()
car2.detail_info_after()
print('-'*50)

# Static λ©”μ†Œλ“œ 호좜 2가지 방법
# 1. μΈμŠ€ν„΄μŠ€λ‘œ ν˜ΈμΆœν•˜κΈ°
print(car1.is_hyundai(car1))
print(car2.is_hyundai(car2))
# 2. 클래슀둜 ν˜ΈμΆœν•˜κΈ°
print(Car.is_hyundai(car1))
print(Car.is_hyundai(car2))

 

  • @classmethod : 클래슀 λ©”μ†Œλ“œλ₯Ό 의미. νŒŒλΌλ―Έν„°μ— clsλΌλŠ” κ³ μ • νŒŒλΌλ―Έν„°κ°€ λ“€μ–΄κ°€κ³  perμ΄λΌλŠ” optionalν•œ νŒŒλΌλ―Έν„° μΆ”κ°€ κ°€λŠ₯. 주둜 클래슀 μ•ˆμ—μ„œ μ •μ˜λœ 클래슀 λ³€μˆ˜λ₯Ό μ΄μš©ν•΄μ„œ customizing ν•  λ•Œ μ‚¬μš©λ¨
  • @staticmethod : 정적 λ©”μ†Œλ“œλ₯Ό 의미. 클래슀 λ³€μˆ˜λ₯Ό μ΄μš©ν•˜λŠ” 것은 μ•„λ‹ˆμ§€λ§Œ λ§Œλ“€μ–΄μ§„ μ—¬λŸ¬κ°œ μΈμŠ€ν„΄μŠ€λ₯Ό μ΄μš©ν•΄μ„œ 무엇인가 ν•˜κ³  싢을 λ•Œ, 즉 μœ λ™μ μœΌλ‘œ λ™μž‘μ„ ν•˜λ„λ‘ ν•˜κΈ° μœ„ν•΄ 주둜 μ •μ˜λ¨.(μ˜ˆμ‹œλŠ” μœ„ μ½”λ“œμ˜ 주석을 μ‚΄νŽ΄λ³΄μž) κ³ μ • νŒŒλΌλ―Έν„°λŠ” μ‘΄μž¬ν•˜μ§€ μ•Šμ§€λ§Œ selfκ°€ μ•„λ‹Œ κ·Έλƒ₯ 일반 νŒŒλΌλ―Έν„°λ₯Ό λ„£μ–΄μ£Όκ³  νŒŒλΌλ―Έν„°μ— 클래슀λ₯Ό μ •μ˜ν•˜λ©΄μ„œ λ§Œλ“€μ–΄μ€€ μΈμŠ€ν„΄μŠ€ 객체λ₯Ό λ„£μ–΄μ£ΌλŠ” 게 일반적
λ°˜μ‘ν˜•