인프런 파이썬 중급 - 클래스&메소드 심화
- 노트필기/파이썬
- 2021. 4. 28.
In [1]:
# 클래스 구조
class Car():
"""
Car class
Author : Kim
Date : 2021.04.25
"""
# 클래스 변수(모든 인스턴스가 공유)
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 __del__(self):
Car.car_count -= 1
def detail_info(self):
print('Current ID : {}'.format(id(self)))
print('Car Detail Info : {} {}'.format(self._company, self._details.get('price')))
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})
In [2]:
print(id(car1))
print(id(car2))
print(id(car3))
1861401257440
1861401257536
1861401257488
In [3]:
print(car1._company == car2._company)
print(car1 is car2)
False
False
In [4]:
# dir & __dict__
# __dict__는
In [5]:
print(dir(car1))
['__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_company', '_details', 'car_count', 'detail_info']
In [6]:
print(car1.__dict__)
{'_company': 'Ferrari', '_details': {'color': 'White', 'horsepower': 400, 'price': 8000}}
In [7]:
print(Car.__doc__)
Car class
Author : Kim
Date : 2021.04.25
In [8]:
car1.detail_info()
car2.detail_info()
Current ID : 1861401257440
Car Detail Info : Ferrari 8000
Current ID : 1861401257536
Car Detail Info : BMW 5000
In [9]:
print(car1.__class__, car2.__class__)
print(id(car1.__class__), id(car2.__class__))
<class '__main__.Car'> <class '__main__.Car'>
1861390010688 1861390010688
In [10]:
Car.detail_info()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-05da48ebdf49> in <module>
----> 1 Car.detail_info()
TypeError: detail_info() missing 1 required positional argument: 'self'
In [11]:
Car.detail_info(car1)
Current ID : 1861401257440
Car Detail Info : Ferrari 8000
In [12]:
car1.car_count
Out[12]:
3
In [13]:
Car.car_count
Out[13]:
3
In [14]:
del car2
print(Car.car_count)
2
In [15]:
# 인스턴스 네임스페이스에 없으면 상위에서 검색
# 즉, 동일한 이름으로 변수 생성 가능 -> 인스턴스 검색 후 상위 클래스 변수, 부모클래스 변수
In [26]:
# 기본 인스턴스 메소드
# 클래스 선언
class Car(object):
'''
Car Class
Author : Me
Date : 2021.04.26
Description : Class, Static, Instance Method
'''
# Class Variable (모든 인스턴스가 공유)
car_count = 0
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')))
def get_price(self):
return 'Before Car Price -> company : {}, price : {}'.format(self._company, self._details.get('price'))
def get_price_culc(self):
return 'After Car Price -> company : {}, price : {}'.format(self._company, self._details.get('price')*Car.price_per_raise)
@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')
@staticmethod
def is_bmw(inst):
if inst._company == "Bmw":
return 'OK! This car is {}'.format(inst._company)
return 'Sorry. This car is not Bmw'
# 자동차 인스턴스
car1 = Car('Bmw', {'color' : 'Black', 'horsepower': 270, 'price': 5000})
car2 = Car('Audi', {'color' : 'Silver', 'horsepower': 300, 'price': 6000})
In [27]:
car1.detail_info()
Current Id : 1861402149360
Car Detail Info : Bmw 5000
In [28]:
print(car1._details.get('price'))
5000
In [29]:
# 가격정보(인상 전)
print(car1.get_price())
Before Car Price -> company : Bmw, price : 5000
In [30]:
Car.price_per_raise = 1.4
In [31]:
print(car1.get_price_culc())
After Car Price -> company : Bmw, price : 7000.0
In [32]:
Car.raise_price(1.6)
Succeed! price increased
In [33]:
print(car1.get_price_culc())
After Car Price -> company : Bmw, price : 8000.0
In [34]:
print(car1.is_bmw(car1))
OK! This car is Bmw
In [35]:
print(Car.is_bmw(car1))
print(Car.is_bmw(car2))
OK! This car is Bmw
Sorry. This car is not Bmw