티스토리 뷰

연락처(이름, 전화번호, 이메일)을 추가, 삭제, 검색, 합치기(연락처+연락처) 등의 기능을 가진 클래스를 구현해 보자 

 

class Contact:
    def __init__(self, name=None, phone=None):
        self.name = name
        self.phone = phone

    def __eq__(self, other):
        return any([v1 == v2 for v1, v2 in zip(self.__dict__.values(), other.__dict__.values())])

    def __str__(self):
        return f"{self.__dict__}"


class Book:
    def __init__(self, pages=None):
        self.pages = pages if pages else list()

    def add(self, page):
        self.pages.append(page)

    def index(self, page):
        return self.pages.index(page) if page in self.pages else None

    def __contains__(self, page):
        return page in self.pages

    def __add__(self, other):
        return Book(self.pages + other.pages)

    def __str__(self):
        return "\n".join(map(str, self.pages))


book1 = Book()
book1.add(Contact("kim", "010-2222-3333"))
book1.add(Contact("lee", "010-2222-4444"))
contact = Contact(phone="010-2222-44444", name="lee")
if contact in book1:
    print(book1.index(contact))
book2 = Book()
book2.add(Contact("choi", "010-2222-5555"))
book1 += book2
print(book1)

 

하드코딩 하지 않고 명령어로 구현

class Person:
    def __init__(self, name=None, phone=None):
        self.name = name
        self.phone = phone

    def __eq__(self, other):
        return any([v1 == v2 for v1, v2 in zip(self.__dict__.values(), other.__dict__.values())])

    def __str__(self):
        return f"{self.__dict__}"


class Book(list):
    def filter(self, t):
        return tuple([i for i, v in enumerate(self) if v == t])

    def __str__(self):
        return "\n".join(map(str, self))


if __name__ == '__main__':
    """
    Example
    >>> add James_Kim 010-1234-5678
    >>> find James_kim _
    >>> find _ 010-1234-5678
    """
    functions = {"add": lambda ins, param, cls: ins.append(cls(*param)),
                 "find": lambda ins, param, cls: ins.filter(cls(*param))}
    contact = Book()
    while True:
        commend, *params = input().split(" ")
        if commend in functions and len(params) is len(Person().__dict__):
            print(f"result={functions[commend](contact, params, Person)}\n{contact}")
        else:
            print("Invalid instruction")


댓글