python class自身返回值研究

  • 2021 年 10 月 5 日
  • 筆記

在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的基本資訊

 

Tags: