欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python模擬重載初始化函數(shù)的方法詳解

 更新時(shí)間:2024年11月15日 09:17:37   作者:仙草哥哥  
重載初始化函數(shù),是指同一個(gè)類中定義了多個(gè)構(gòu)造函數(shù),可以通過多種不同的方法進(jìn)行構(gòu)造,下面我們就來看看在python中如何實(shí)現(xiàn)類似的功能吧

重載初始化函數(shù)

重載初始化函數(shù),是指同一個(gè)類中定義了多個(gè)構(gòu)造函數(shù),可以通過多種不同的方法進(jìn)行構(gòu)造。

舉例來說,如果我們創(chuàng)建了一個(gè)學(xué)生類,在創(chuàng)建學(xué)生的時(shí)候,需要提供學(xué)生的姓名以及出生日期,對(duì)于出生日期,我們考慮可以使用date對(duì)象,直接進(jìn)行初始化。也可以分別使用年,月,日進(jìn)行初始化?;蛘哌€可以使用例如2024-11-14日這樣的時(shí)間字符串進(jìn)行初始化。

在python中并沒有直接的函數(shù)重載,但是,我們有多種方法可以實(shí)現(xiàn)類似的功能。

python實(shí)現(xiàn)

根據(jù)對(duì)象類型

這種方法根據(jù)傳入的參數(shù)的類型不同,從而實(shí)現(xiàn)通過不同的方法進(jìn)行解析。但是缺點(diǎn)是在類型多的情況下,代碼變得非常復(fù)雜。

from datetime import date
 
class Student:
    def __init__(self, name, birth_date):
        if isinstance(birth_date, date):
            self.birth_date = birth_date
        elif isinstance(birth_date, str):
            try:
                year, month, day = map(int, birth_date.split("-"))
                self.birth_date = date(year, month, day)
            except ValueError:
                raise ValueError("日期字符串格式應(yīng)為YYYY-MM-DD")
        elif isinstance(birth_date, tuple) and len(birth_date) == 3:
            year, month, day = birth_date
            self.birth_date = date(year, month, day)
        else:
            raise TypeError("birth_date必須是date對(duì)象,YYYY-MM-DD格式的字符串,或(年, 月, 日)的元組")
 
        self.name = name
 
    def __str__(self):
        return f"Student(name={self.name}, birth_date={self.birth_date})"
 
 
student1 = Student("sagegrass", date(2011, 11, 11))
student2 = Student("sagegrass", "2011-11-11")
student3 = Student("sagegrass", (2011, 11, 11))
 
print(student1)
print(student2)
print(student3)

使用類方法

通常情況下,使用類方法被認(rèn)為是最好的實(shí)踐方法,唯一的缺點(diǎn)在于,與常規(guī)的初始化略有不同,因此一些用戶可能不能適應(yīng)。

from datetime import date
 
class Student:
    def __init__(self, name, birth_date):
        if not isinstance(birth_date, date):
            raise TypeError("birth_date必須是datetime.date類型")
        self.name = name
        self.birth_date = birth_date
        
    @classmethod
    def from_string(cls, name, birth_date_str):
        try:
            year, month, day = map(int, birth_date_str.split("-"))
            birth_date = date(year, month, day)
            return cls(name, birth_date)
        except ValueError:
            raise ValueError("日期字符串格式應(yīng)為YYYY-MM-DD")
 
    @classmethod
    def from_year_month_day(cls, name, year, month, day):
        try:
            birth_date = date(year, month, day)
            return cls(name, birth_date)
        except ValueError:
            raise ValueError("日期無效,請(qǐng)使用正確的年月日")
 
    def __str__(self):
        return f"Student(name={self.name}, birth_date={self.birth_date})"
 
 
student1 = Student("sagegrass", date(2011, 11, 11))
student2 = Student.from_string("sagegrass", "2011-11-11")           
student3 = Student.from_year_month_day("sagegrass", 2011, 11, 11)   
 
print(student1)
print(student2)
print(student3)

使用靜態(tài)方法

如果將之前使用的類方法,改為靜態(tài)方法,也是可行的,這樣無需再訪問類本身。

from datetime import date
 
class Student:
    
    def __init__(self, name, birth_date):
        if not isinstance(birth_date, date):
            raise TypeError("birth_date必須是datetime.date類型")
        self.name = name
        self.birth_date = birth_date
    
    @staticmethod
    def from_year_month_day(name, year, month, day):
        try:
            birth_date = date(year, month, day)
            return Student(name, birth_date)
        except ValueError:
            raise ValueError("日期無效,請(qǐng)使用正確的年月日")
 
    def __str__(self):
        return f"Student(name={self.name}, birth_date={self.birth_date})"
       
        
student = Student.from_year_month_day("sagegrass", 2011, 11, 11)   
 
print(student)

但是需要注意的是,通常情況下,應(yīng)該優(yōu)先使用類方法而非靜態(tài)方法。因?yàn)樵诎^承關(guān)系的情況下,類方法可以總是保證返回的是子類的實(shí)例。而靜態(tài)方法則會(huì)返回父類的實(shí)例,從而出現(xiàn)不符合預(yù)期的情況。

使用帶默認(rèn)值的參數(shù)

當(dāng)提供了大量的默認(rèn)值參數(shù),初始化函數(shù)會(huì)變得復(fù)雜和難以理解,缺點(diǎn)與根據(jù)對(duì)象類型初始化相似。

from datetime import date
 
class Student:
    
    def __init__(self, name, birth_date=None, year=None, month=None, day=None):
        if birth_date is not None:
            if not isinstance(birth_date, date):
                raise TypeError("birth_date必須是datetime.date類型")
            self.birth_date = birth_date
        elif all([year, month, day]):
            try:
                self.birth_date = date(year, month, day)
            except ValueError:
                raise ValueError("日期無效,請(qǐng)使用正確的年月日")
        else:
            raise ValueError("必須提供birth_date或者年月日的組合")
 
        self.name = name
 
    def __str__(self):
        return f"Student(name={self.name}, birth_date={self.birth_date})"
        
 
student1 = Student("sagegrass", birth_date=date(2011, 11, 11))  
student2 = Student("sagegrass", year=2011, month=11, day=11)    
 
print(student1)
print(student2)

并且,使用該方法通常無法同時(shí)滿足使用位置參數(shù)進(jìn)行傳入,因此也可以考慮禁止使用位置參數(shù)。

# 禁用位置參數(shù)
def __init__(self, name, *, birth_date=None, year=None, month=None, day=None):
    pass
 
# 或者允許birth_date使用位置參數(shù),但不允許年月日用
def __init__(self, name, birth_date=None, *, year=None, month=None, day=None):
    pass

到此這篇關(guān)于python模擬重載初始化函數(shù)的方法詳解的文章就介紹到這了,更多相關(guān)python重載初始化函數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python實(shí)現(xiàn)不同樣式二維碼

    Python實(shí)現(xiàn)不同樣式二維碼

    作為一名合格的?Python?程序員,在工作中必然會(huì)用到二維碼相關(guān)操作,那如何快速的用?Python?實(shí)現(xiàn)呢?別著急,咱們這篇博客就為你解決
    2023-01-01
  • Pycharm學(xué)生免費(fèi)專業(yè)版安裝教程的方法步驟

    Pycharm學(xué)生免費(fèi)專業(yè)版安裝教程的方法步驟

    這篇文章主要介紹了Pycharm學(xué)生免費(fèi)專業(yè)版安裝教程的方法步驟,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • 利用Python實(shí)現(xiàn)在同一網(wǎng)絡(luò)中的本地文件共享方法

    利用Python實(shí)現(xiàn)在同一網(wǎng)絡(luò)中的本地文件共享方法

    今天小編就為大家分享一篇利用Python實(shí)現(xiàn)在同一網(wǎng)絡(luò)中的本地文件共享方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-06-06
  • pow在python中的含義及用法

    pow在python中的含義及用法

    在本篇文章里小編給各位分享了關(guān)于pow在python中是什么意思的相關(guān)知識(shí)點(diǎn)內(nèi)容,有需要的朋友們參考學(xué)習(xí)下。
    2019-07-07
  • python用來獲得圖片exif信息的庫實(shí)例分析

    python用來獲得圖片exif信息的庫實(shí)例分析

    這篇文章主要介紹了python用來獲得圖片exif信息的庫,實(shí)例分析了exif-py庫文件的使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-03-03
  • python空值填充為無的實(shí)現(xiàn)方法

    python空值填充為無的實(shí)現(xiàn)方法

    我們經(jīng)常會(huì)遇到數(shù)據(jù)集中存在空值的情況,本文主要介紹了python空值填充為無的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-02-02
  • 基于Python制作簡(jiǎn)易的windows修改器

    基于Python制作簡(jiǎn)易的windows修改器

    現(xiàn)在應(yīng)該大部分人都使用win11系統(tǒng)吧,win11其實(shí)挺好用哈,只是有一點(diǎn)不好用,就是右鍵的菜單,今天做個(gè)小程序,就是應(yīng)該修改win11的一個(gè)應(yīng)用程序,感興趣的可以了解一下
    2022-08-08
  • pytorch中的dataset用法詳解

    pytorch中的dataset用法詳解

    這篇文章主要介紹了pytorch的dataset用法詳解,當(dāng)我們繼承了一個(gè)?Dataset類之后,我們需要重寫?len?方法,該方法提供了dataset的大??;?getitem?方法,?該方法支持從?0?到?len(self)的索引,下面來看看附有代碼的講解吧,希望對(duì)你的學(xué)習(xí)或者工作有所幫助
    2022-01-01
  • 解決numpy矩陣相減出現(xiàn)的負(fù)值自動(dòng)轉(zhuǎn)正值的問題

    解決numpy矩陣相減出現(xiàn)的負(fù)值自動(dòng)轉(zhuǎn)正值的問題

    這篇文章主要介紹了解決numpy矩陣相減出現(xiàn)的負(fù)值自動(dòng)轉(zhuǎn)正值的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • Python列表如何更新值

    Python列表如何更新值

    在本篇內(nèi)容中小編給大家整理的是一篇關(guān)于Python列表如何更新值的知識(shí)點(diǎn),需要的朋友們可以學(xué)習(xí)下。
    2020-05-05

最新評(píng)論