Python – __init__ , __str__ , __repr__

測試環境為 CentOS 8 x86_64 (虛擬機)

__init__ , __str__ , __repr__ 是 Class 預設 method .下面來看一下使用的時機點.

  • object.__init__(self[, …]) – https://docs.python.org/3/reference/datamodel.html#object.__init__
    建構函式, 在建立新的 實體 (instance) 後會呼叫使用.
  • object.__str__(self) – https://docs.python.org/3/reference/datamodel.html#object.__str__
    可以透過 str(object) 呼叫使用或是透過內建函數 format() 與 print() 直接使用.
  • object.__repr__(self) – https://docs.python.org/3/reference/datamodel.html#object.__repr__
    可以透過內建函數 repr() 呼叫使用.

Class 範例如下.

[root@localhost ~]# vi computer3.py
# Computer Class
class Computer:
    # Constructor
    def __init__(self , brand , color):
        # Attribute
        self.brand = brand
        self.color = color

    # Method
    def __str__(self):
       return f"STR: This Computer brand is {self.brand} and Color is {self.color}."
    def __repr__(self):
       return f"REPR: This Computer brand is {self.brand} and Color is {self.color}."

#Object
Customer1=Computer("apple","sliver")

print (Customer1)
print (str(Customer1))

print (repr(Customer1))

執行結果

[root@localhost ~]# python3 computer3.py
STR: This Computer brand is apple and Color is sliver.
STR: This Computer brand is apple and Color is sliver.
REPR: This Computer brand is apple and Color is sliver.

說明:

  • __init__
    建構式 (Constructor) __init__() method (方法) 是 Class 預設 method 之一 ,會在建立 instance 後執行.

    需 self 參數(代表該物件的本身),其他輸入參數使用逗號來區隔.

        def __init__(self , brand , color):
            # Attribute
            self.brand = brand
            self.color = color
    

    建立 instance .

    Customer1=Computer("apple","sliver")
    
  • __str__
    透過 str() 或是直接使用 print (instance) 時.

        def __str__(self):
           return f"STR: This Computer brand is {self.brand} and Color is {self.color}."
    
    print (Customer1)
    print (str(Customer1))
    

    執行結果

    STR: This Computer brand is apple and Color is sliver.
    STR: This Computer brand is apple and Color is sliver.
    
  • __repr__
    透過 repr() 時.

        def __repr__(self):
           return f"REPR: This Computer brand is {self.brand} and Color is {self.color}."
    
    print (repr(Customer1))
    

    執行結果

    REPR: This Computer brand is apple and Color is sliver.
    

__str__ , __repr__ 使用上是有差別的,很多說明使用時間當作範例來看他們之間的差異性.

[root@localhost ~]# python3
Python 3.6.8 (default, Mar 25 2022, 11:15:52) 
[GCC 8.5.0 20210514 (Red Hat 8.5.0-10)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> today = datetime.datetime.now()
  • __str__
    建議使用於用戶端.

    >>> print(str(today))
    2022-05-18 21:07:11.455780
    
  • __repr__
    建議使用於開發人員.

    >>> print(repr(today))
    datetime.datetime(2022, 5, 18, 21, 7, 11, 455780)
    
沒有解決問題,試試搜尋本站其他內容

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料