[Python]클래스

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

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

class Car():
    def __init__(self, company, details):
        self._company = company
        self._details = details

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

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


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(car1) # __str__ 가 출력된다.
print(car2)
print(car3)

""" 결과
str : Tesla - {'color': 'black', 'horespower': 300, 'price': 5000}
str : Bmw - {'color': 'red', 'horespower': 400, 'price': 6000}
str : Audi - {'color': 'white', 'horespower': 250, 'price': 4000}
"""

print()

print(car1.__dict__) # 매직매서드, 해당 Object의 속성(필드) 정보를 표시해준다.
print(car2.__dict__)
print(car3.__dict__)

""" 출력결과
{'_company': 'Tesla', '_details': {'color': 'black', 'horespower': 300, 'price': 5000}}
{'_company': 'Bmw', '_details': {'color': 'red', 'horespower': 400, 'price': 6000}}
{'_company': 'Audi', '_details': {'color': 'white', 'horespower': 250, 'price': 4000}}
"""

car_list = []
car_list.append(car1)
car_list.append(car2)
car_list.append(car3)

print(car_list) # __repr__ 이 출력된다.
""" 출력결과
[repr : Tesla - {'color': 'black', 'horespower': 300, 'price': 5000}, repr : Bmw - {'color': 'red', 'horespower': 400, 'price': 6000}, repr : Audi - {'color': 'white', 'horespower': 250, 'price': 4000}]
"""

print()

for x in car_list:
    print(x) # __str__ 이 출력됨

""" 출력결과
str : Tesla - {'color': 'black', 'horespower': 300, 'price': 5000}
str : Bmw - {'color': 'red', 'horespower': 400, 'price': 6000}
str : Audi - {'color': 'white', 'horespower': 250, 'price': 4000}
"""

You may also like...

답글 남기기

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