在類中定義多個構造函數


說到Python中的類構造函數,一般是實現類的__init__方法,用以實例初始化(__new__用作創建實例)。
但Python不像Java有很顯示的方法重載。因此,若要實現多個不同的構造函數,可能需要另辟蹊徑。
一個方案是使用類方法classmethod,如下:

import time

class Date:
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    @classmethod
    def today(cls):
        t = time.localtime()
        return cls(t.tm_year, t.tm_mon, t.tm_mday)


a = Date(2012, 12, 21) # Primary
b = Date.today() # Alternate

如果不實用classmethod,可能想到另一種方案,以允許不同調用約定的方式實現__init __()方法。如下:

class Date:
    def __init__(self, *args):
        if len(args) == 0:
            t = time.localtime()
            args = (t.tm_year, t.tm_mon, t.tm_mday)
        self.year, self.month, self.day = args

盡管這種方式看起來可以解決問題,但是該方案使得代碼難以理解和維護。例如,此實現不會顯示有用的幫助字符串(帶有參數名稱)。 另外,創建Date實例的代碼將不太清楚。

a = Date(2012, 12, 21)    # Clear. A specific date. 
 b = Date()               #  ??? What does this do?

# Class method version
c = Date.today()          # Clear. Today's date.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM