W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
你想實(shí)現(xiàn)一個(gè)類(lèi),除了使用 __init__()
方法外,還有其他方式可以初始化它。
為了實(shí)現(xiàn)多個(gè)構(gòu)造器,你需要使用到類(lèi)方法。例如:
import time
class Date:
"""方法一:使用類(lèi)方法"""
# 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)
直接調(diào)用類(lèi)方法即可,下面是使用示例:
a = Date(2012, 12, 21) # Primary
b = Date.today() # Alternate
類(lèi)方法的一個(gè)主要用途就是定義多個(gè)構(gòu)造器。它接受一個(gè) class
作為第一個(gè)參數(shù)(cls)。你應(yīng)該注意到了這個(gè)類(lèi)被用來(lái)創(chuàng)建并返回最終的實(shí)例。在繼承時(shí)也能工作的很好:
class NewDate(Date):
pass
c = Date.today() # Creates an instance of Date (cls=Date)
d = NewDate.today() # Creates an instance of NewDate (cls=NewDate)
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: