8.16 在類中定義多個構造器

2018-02-24 15:26 更新

問題

你想實現(xiàn)一個類,除了使用 __init__() 方法外,還有其他方式可以初始化它。

解決方案

為了實現(xiàn)多個構造器,你需要使用到類方法。例如:

import time

class Date:
    """方法一:使用類方法"""
    # Primary constructor
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    # Alternate constructor
    @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

討論

類方法的一個主要用途就是定義多個構造器。它接受一個 class 作為第一個參數(shù)(cls)。你應該注意到了這個類被用來創(chuàng)建并返回最終的實例。在繼承時也能工作的很好:

class NewDate(Date):
    pass

c = Date.today() # Creates an instance of Date (cls=Date)
d = NewDate.today() # Creates an instance of NewDate (cls=NewDate)
以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號