python class自身返回值研究


在python中,如果你寫了這樣一串代碼:

import datetime

a = datetime.date(2021, 9, 1)
b = "2021-09-01"
print(a, b)
print([a, b])
print(type(a), type(b))

你會發現 a 是一個datetime.date的類

而b是個字符串

但在輸出時,卻出現了這樣的結果

2021-09-01 2021-09-01
[datetime.date(2021, 9, 1), '2021-09-01']
<class 'datetime.date'> <class 'str'>

可以發現,在a單獨輸出時,竟然輸出了字符串!

而a的類型依然是datetime.date的類

這是怎么回事呢

要知道,在python中定義一個類,輸出這個類會輸出這個類的信息

class test:
    pass


a = test()
print(a)

輸出:

<__main__.test object at 0x000001B344057070>

那為什么datetime.date返回的不是以上輸出的,而是一個字符串呢?

我就打開了datetime.py一看究竟

結果發現了幾行代碼

 

 

可以看到使用了__repr__

通過我仔細的研究

我發現__repr__可以修改class的輸出信息

class test:
    def __repr__(self):
        return "This is a class"


a = test()
print(a)

輸出:

This is a class

 又回到開頭的問題

可以看到在數組輸出是已經可以輸出__repr__修改過的信息

但是在單獨輸出是,還是輸出了與__repr__不同的信息

於是我又打開了datetime.py

 

看到了__str__可以定義class的格式

不過__str__需要賦值一個函數的名稱

class test:
    def __repr__(self):
        return "This is a class"

    def make(self):
        return "You make a class"

    __str__ = make


a = test()
print(a)

輸出:

You make a class

總結

從datetime的發現中學到了很多關於class的更深入的使用

可以使用__repr__和__str__設置class的基本信息

 


免責聲明!

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



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