Python – __init__ , __str__ , __repr__

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

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

  • object.__new__(cls[, …]) – https://docs.python.org/3/reference/datamodel.html#object.__new__
    建構函式, Called to create a new instance of class cls. __new__()
  • object.__str__(self) – https://docs.python.org/3/reference/datamodel.html#object.__str__
    Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object.
  • object.__repr__(self) – https://docs.python.org/3/reference/datamodel.html#object.__repr__
    Called by the repr() built-in function to compute the “official” string representation of an object

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"This Computer brand is {self.brand} and Color is {self.color}."
    def __repr__(self):
       return f"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
This Computer brand is apple and Color is sliver.
This Computer brand is apple and Color is sliver.
This Computer brand is apple and Color is sliver.

說明:

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

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

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

    建立物件時.

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

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

    執行結果

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

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

    執行結果

    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 如何處理網站訪客的留言資料