Python Level 2 Ch.2

phillip yoonΒ·2021λ…„ 6μ›” 27일

πŸ“Œ Chapter 2


πŸ’‘Code

# 객체 μ§€ν–₯ ν”„λ‘œκ·Έλž˜λ°(OOP) -> μ½”λ“œμ˜ μž¬μ‚¬μš©, μ½”λ“œ 쀑볡 λ°©μ§€, μœ μ§€λ³΄μˆ˜, λŒ€ν˜•ν”„λ‘œμ νŠΈ
# 규λͺ¨κ°€ 큰 ν”„λ‘œμ νŠΈ(ν”„λ‘œκ·Έλž¨) -> ν•¨μˆ˜ 쀑심 -> 데이터 λ°©λŒ€ -> 볡작
# 클래슀 쀑심 -> 데이터 쀑심 -> 객체둜 관리

# 일반적인 μ½”λ”©
# μ°¨λŸ‰1

car_company = 'Ferrari'
car_detail_1 = [
    {'color' : 'White'},
    {'Hp' : '400'},
    {'price' : '8000'}
]
car_company2 = 'BMW'
car_detail_2 = [
    {'color' : 'Black'},
    {'Hp' : '270'},
    {'price' : '5000'}
]
car_company3 = 'Audi'
car_detail_3 = [
    {'color' : 'Silver'},
    {'Hp' : '300'},
    {'price' : '6000'}
]

# 리슀트 ꡬ쑰
# κ΄€λ¦¬ν•˜κΈ° 뢈편
# 인덱슀 μ ‘κ·Ό μ‹œ μ‹€μˆ˜ κ°€λŠ₯μ„±, μ‚­μ œ 뢈편
car_company_list = ['Ferrari', 'BMW', 'Audi']
car_detail_list = [
    {'color' : 'White', 'Hp' : '400', 'price' : '8000'},
    {'color' : 'Black', 'Hp' : '270', 'price' : '5000'},
    {'color' : 'Silver', 'Hp' : '300', 'price' : '6000'}
]
del car_detail_list[1]
del car_company_list[1]
print(car_company_list)
print(car_detail_list)

print()
print()

# λ”•μ…”λ„ˆλ¦¬ ꡬ쑰
# μ½”λ“œ 반볡 지속, 쀑첩 문제(ν‚€), ν‚€ 쑰회 μ˜ˆμ™Έ 처리 λ“±
car_dicts = [
    {'car_company' : 'Ferrari', 'car_detail' : {'color' : 'White', 'Hp' : '400', 'price' : '8000'}},
    {'car_company': 'Bmw', 'car_detail': {'color' : 'Black', 'horsepower': 270, 'price': 5000}},
    {'car_company': 'Audi', 'car_detail': {'color' : 'Silver', 'horsepower': 300, 'price': 6000}}
]
del car_dicts[1]
print(car_dicts)
print()
print()

# 클래슀 ꡬ쑰
# ꡬ쑰 섀계 ν›„ μž¬μ‚¬μš©μ„± 증가, μ½”λ“œ 반볡 μ΅œμ†Œν™”, λ©”μ†Œλ“œ ν™œμš©
class Car():
    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)

car1 = Car('Ferrari', {'color' : 'White', 'horsepower': 400, 'price': 8000})
car2 = Car('Bmw', {'color' : 'Black', 'horsepower': 270, 'price': 5000})
car3 = Car('Audi', {'color' : 'Silver', 'horsepower': 300, 'price': 6000})

print(car1.__dict__)
print(car2.__dict__)
print(car3.__dict__)

# 리슀트 μ„ μ–Έ
car_list = []
car_list.append(car1)
car_list.append(car2)
car_list.append(car3)
print()
print(car_list)
print()
print()

# 반볡 (__str__)
for x in car_list:
    print(repr(x))
    # print(x)
# 클래슀 상세 μ„€λͺ…
# 클래슀 λ³€μˆ˜, μΈμŠ€ν„΄μŠ€ λ³€μˆ˜

# 클래슀 재 μ„ μ–Έ
class Car():
    """
    Car class
    Author : Kim
    Date: 2021.04.03
    """
    # 클래슀 λ³€μˆ˜
    car_count = 0
    def __init__(self, company, details):
        self._company = company
        self._details = details
        Car.car_count += 1
    def __str__(self):
        return 'str : {} - {}'.format(self._company, self._details)
    def __repr__(self):
        return 'repr : {} - {}'.format(self._company, self._details)
    def detail_info(self):
        print('Current Id : {}'.format(id(self)))
        print('Car Detail info : {} {}'.format(self._company, self._details.get('price')))
    def __del__(self):
        Car.car_count -= 1

# Self 의미
car1 = Car('Ferrari', {'color' : 'White', 'horsepower': 400, 'price': 8000})
car2 = Car('Bmw', {'color' : 'Black', 'horsepower': 270, 'price': 5000})
car3 = Car('Audi', {'color' : 'Silver', 'horsepower': 300, 'price': 6000})

# id 확인
print(id(car1))
print(id(car2))
print(id(car3))

print(car1._company == car2._company)
print(car1 is car2)

# dir & __dict__ 확인
print(dir(car1))
print(dir(car2))
print()
print()

print(car1.__dict__)
print(car2.__dict__)

# Doctring
print(Car.__doc__)
print()

# μ‹€ν–‰
car1.detail_info()
car2.detail_info()

# Error
# Car.detail_info()
Car.detail_info(car1)
Car.detail_info(car2)

# 비ꡐ
print(car1.__class__, car2.__class__)
print(id(car1.__class__) == id(car3.__class__))
print()

# μΈμŠ€ν„΄μŠ€ λ³€μˆ˜
# 직접 μ ‘κ·Ό(PEP λ¬Έλ²•μ μœΌλ‘œ ꢌμž₯ X)
print(car1._company, car2._company)
print(car2._company, car3._company)

print()
print()

# 클래슀 λ³€μˆ˜
# μ ‘κ·Ό
print(car1.car_count)
print(car2.car_count)
print(Car.car_count)
print()
print()

# 곡유 확인
print(Car.__dict__)
print(car1.__dict__)
print(car2.__dict__)
print(car3.__dict__)

# μΈμŠ€ν„΄μŠ€ λ„€μž„μŠ€νŽ˜μ΄μŠ€ μ—†μœΌλ©΄ μƒμœ„μ—μ„œ 검색
# 즉, λ™μΌν•œ μ΄λ¦„μœΌλ‘œ λ³€μˆ˜ 생성 κ°€λŠ₯(μΈμŠ€ν„΄μŠ€ 검색 ν›„ -> μƒμœ„(클래슀 λ³€μˆ˜, λΆ€λͺ¨ 클래슀 λ³€μˆ˜))
del car2
print(car1.car_count)
print(car3.car_count)
# 클래슀 λ©”μ†Œλ“œ, μΈμŠ€ν„΄μŠ€ λ©”μ†Œλ“œ, μŠ€ν…Œν‹± λ©”μ†Œλ“œ

class Car():
    """
    Car class
    Author : Kim
    Date: 2021.04.03
    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
    def raise_price(cls,per):
        if per <=1:
            print('Please Enter 1 or More')
            return
        cls.price_per_raise = per
        return 'Succeed! Price Incresed.'
    # 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})
# κΈ°λ³Έ 정보
print(car1)
print(car2)
print()
# 전체 정보
car1.detail_info()
car2.detail_info()
print()
# 가격 정보(인상 μ „)
print(car1.get_price())
print(car2.get_price())
print()

# 가격 인상(클래슀 λ©”μ†Œλ“œ μ‚¬μš©)
Car.price_per_raise = 1.2

# 가격 정보(인상 ν›„)
print(car1.get_price_culc())
print(car2.get_price_culc())

# 가격 인상(클래슀 λ©”μ†Œλ“œ μ‚¬μš©)
Car.raise_price(1.6)
print()
# 가격 정보(인상 ν›„ : 클래슀 λ©”μ†Œλ“œ)
print(car1.get_price_culc())
print(car2.get_price_culc())
# μΈμŠ€ν„΄μŠ€λ‘œ 호좜(μŠ€ν…Œν‹±)
print(car1.is_Bmw(car1))
print(car2.is_Bmw(car2))
# 클래슀둜 호좜(μŠ€ν…Œν‹±)
print(Car.is_Bmw(car1))
print(Car.is_Bmw(car2))
print(Car.__doc__)
profile
세상이 더 λ‚˜μ•„μ§€κΈ°λ₯Ό λ°”λΌλŠ” 마음으둜 κ°œλ°œμ— μž„ν•˜κ³  μžˆμŠ΅λ‹ˆλ‹€.

0개의 λŒ“κΈ€