建構式有許多限制,也無法用名稱表達意涵,但工廠函式可以。

Replace Constructor with Factory Function

# Before
class Book:
    def __init__(self, title, author, genre):
        self.title = title
        self.author = author
        self.genre = genre

book = Book("1984", "George Orwell", "Dystopian")

# After
class Book:
    def __init__(self, title, author, genre):
        self.title = title
        self.author = author
        self.genre = genre

    @classmethod
    def create_book(cls, title, author, genre):
        return cls(title, author, genre)

book = Book.create_book("1984", "George Orwell", "Dystopian")