지난 시간에 이어 이번 시간 역시 객체 지향 코딩에 대해서 공부할 예정이다.
class car () :
"""
car class
Author : kim young mok
Date : 2021. 7. 29
"""
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
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})
여기까지 class를 설정하고 클래스에 맞게 변수를 입력했다.
a. ID값 확인
print(id(car1)) = 1674714071776
print(id(car2)) = 1674714071680
위에 보이는 것처럼 서로 다른 인자들끼리는 id값(고유)이 다르다.
b. dir & dict 확인
print(dir(car1))
print(dir(car2))
#예제
['__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']
dir(인자)로 print해보면 해당 안자 속에 들어있는 네임스페이스들을 확인할 수 있다.
print(car1.__dict__)
= {'_company': 'Ferrari', '_details': {'color': 'White', 'horsepower': 400, 'price': 8000}}
print(car2.__dict__)
= {'_company': 'Bmw', '_details': {'color': 'Black', 'horsepower': 270, 'price': 5000}}
여기서 재미있는 점은 인스턴스들 즉, self를 받는 함수들은 반드시 접근시 해당 인자들 car1 car2 등으로 접근해야한다. 하지만 car_count는 클래스로 접근하든 인자로 접근하는 상관없다.