[Python]클래스

파이썬 클래스에 대해 알아보자.

# 클래스에 대해 알아보자.

class Car():
    """
    Car class
    Author Jigi
    """

    # 클래스 변수 : 모든 인스턴스가 공유하는 변수
    car_count = 0

    def __init__(self, company, details): # 생성자
        self._company = company
        self._details = details
        Car.car_count += 1

    def __str__(self):  # 사용자 레벨에서 정보를 출력하고 싶을 때 이용(?)
        return f"str : {self._company} - {self._details}"

    def __repr__(self):  # 개발자 관점에서 객체를 출력하고 싶을 때 이용(?)
        return f"repr : {self._company} - {self._details}"

    def detail_info(self):
        print(f'Current ID : {id(self)}') # self는 클래스의 객체(instance)를 의미한다.
        print(f'Car detail info : {self._company} {self._details.get("price")}')

    def __del__(self): # 소멸자(?)
        print("delete...")
        Car.car_count -= 1


car1 = Car("Tesla", {"color": "black", "horespower": 300, "price": 5000})
car2 = Car("Bmw", {"color": "red", "horespower": 400, "price": 6000})
car3 = Car("Audi", {"color": "white", "horespower": 250, "price": 4000})

print(id(car1))
print(id(car2))
print(id(car3))

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

print()
'''
2143635520048
2143635520096
2143635520432
False
False
'''

# 클래스의 인스턴스 속성값이 dict로 출력
print(car1.__dict__)
print(car2.__dict__)
'''
{'_company': 'Tesla', '_details': {'color': 'black', 'horespower': 300, 'price': 5000}}
{'_company': 'Bmw', '_details': {'color': 'red', 'horespower': 400, 'price': 6000}}

'''

# 주석을 단 부분이 출력됨
print(car1.__doc__)
'''
    Car class
    Author Jigi
'''

car1.detail_info()
car2.detail_info()
''' 결과
Current ID : 2313904994864
Car detail info : Tesla 5000
Current ID : 2313904994912
Car detail info : Bmw 6000
'''
print()
print(car1.__class__, car2.__class__)
print(id(car1.__class__), id(car2.__class__)) # 클래스 자체의 ID, 동일한 클래스의 객체(instance)는 모두 같은 클래스 ID를 갖는다.
''' 결과
<class '__main__.Car'> <class '__main__.Car'>
2143626399952 2143626399952
'''
print()

# 클래스의 속성값이 dict로 출력
print(car1.__dict__)
print(car2.__dict__)
print(dir(car1))

''' 결과
{'_company': 'Tesla', '_details': {'color': 'black', 'horespower': 300, 'price': 5000}}
{'_company': 'Bmw', '_details': {'color': 'red', 'horespower': 400, 'price': 6000}}
['__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']
'''

print()

# 클래스 변수 접근
print(car2.car_count)
print(Car.car_count)
del car2
print(Car.car_count)
'''
3
3
2
'''

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다