Backend/Python

Python 파이썬 생성자, 클래스 예제 03

쏠솔랄라 2023. 7. 4. 13:07

 

 

Exercise3

 

 

Mobile 휴대전화 클래스
단순히 만드는 것에 그치지 말고, 안정성을 높이기 위해 다음과 같이 강제 구현
[1] 이름은 한번 설정하면 절대로 변경할 수 없습니다
[2] 가격은 아무리 싸게 설정해도 40만원 미만은 불가능합니다 ex. 20만원으로 설정시 40만원으로 설정되도록
[3] 통신사나 가격 등은 계속 변경 설정이 가능하도록

(객체 생성 후 아래의 내용을 구현)
     name   telecom price
[1] 갤럭시8 SKT  300000
[2] G6           LG  330000
[3] 아이폰7   KT  510000

아이폰과 갤럭시8의 가격을 비교하여 비싼 휴대폰 이름을 출력

 

 

class Mobile:
    def __init__(self, name, tel=None, price=400000):
        self.__name = name
        self.__tel = tel
        self.price = price

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, name):
        self.__name = name

    @property
    def tel(self):
        return self.__tel

    @tel.setter
    def tel(self, tel):
        self.__tel = tel

    @property
    def price(self):
        return self.__price

    @price.setter
    def price(self, price):
        if price <= 400000:
            self.__price = 400000
        else:
            self.__price = price

    def disp(self):
        print("모델명 : {}".format(self.__name))
        print("통신사 : {}".format(self.__tel))
        print("가격 : {}원".format(self.__price))

    def compare(self, m):
        if self.__price < m.__price:
            print("{}이/가 더 비쌉니다.".format(m.__name))
        elif self.__price > m.__price:
            print("{}이/가 더 비쌉니다.".format(self.__name))
        else:
            print("같다")

    @classmethod
    def compare(cls, m1, m2):
        if m1.__price < m2.__price:
            print("{}이/가 더 비쌉니다.".format(m2.__name))
        elif m1.__price > m2.__price:
            print("{}이/가 더 비쌉니다.".format(m1.__name))
        else:
            print("같다")

    @classmethod
    def mobileList(cls,ls:list):
        print("\tname\ttel\tprice")
        if ls.__len__() == 0:
            print("데이터가 없습니다.")
        else:
            for i in range(ls.__len__()):
                print("[{}]\t{}\t{}\t{}원".format(i+1,ls[i].name,ls[i].tel,ls[i].price))

m1 = Mobile("갤럭시8","SKT",300000)
m2 = Mobile("G6","LGT",330000)
m3 = Mobile("아이폰7","KT",510000)

m1.disp()
m2.disp()
m3.disp()

mobiles = [m1, m2, m3]

Mobile.compare(m1,m3)
Mobile.mobileList(mobiles)

 

 

출력화면