<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Python 對象和類 > 原文: [https://www.programiz.com/python-programming/class](https://www.programiz.com/python-programming/class) #### 在本教程中,您將學習 Python 對象和類的核心功能。 您將學習什么是類,如何創建它并在程序中使用它。 ## Python 對象和類 Python 是一種面向對象的編程語言。 與面向過程的程序設計(主要側重于函數)不同,面向對象的程序設計強調對象。 對象只是數據(變量)和作用于這些數據的方法(函數)的集合。 同樣,類是該對象的藍圖。 我們可以將類視為房子的草圖(原型)。 它包含有關地板,門,窗戶等的所有詳細信息。基于這些描述,我們建造了房屋。 房子是對象。 由于可以根據房屋的藍圖建造許多房屋,因此我們可以根據類創建許多對象。 對象也稱為類的實例,創建該對象的過程稱為**實例化**。 * * * ## 在 Python 中定義一個類 類似的函數定義以 Python 中的[`def`](/python-programming/keyword-list#def)關鍵字開頭,類定義以[`class`](/python-programming/keyword-list#class)關鍵字開頭。 該類中的第一個字符串稱為文檔字符串,并具有有關該類的簡短說明。 盡管不是強制性的,但強烈建議這樣做。 這是一個簡單的類定義。 ```py class MyNewClass: '''This is a docstring. I have created a new class''' pass ``` 一個類創建一個新的本地[命名空間](/python-programming/namespace),其中定義了其所有屬性。 屬性可以是數據或函數。 其中還有一些特殊屬性,它們以雙下劃線`__`開頭。 例如,`__doc__`給我們該類的文檔字符串。 一旦定義了一個類,就會創建一個具有相同名稱的新類對象。 這個類對象使我們可以訪問不同的屬性以及實例化該類的新對象。 ```py class Person: "This is a person class" age = 10 def greet(self): print('Hello') # Output: 10 print(Person.age) # Output: <function Person.greet> print(Person.greet) # Output: 'This is my second class' print(Person.__doc__) ``` **輸出** ```py 10 <function Person.greet at 0x7fc78c6e8160> This is a person class ``` * * * ## 用 Python 創建對象 我們看到了類對象可以用來訪問不同的屬性。 它也可以用來創建該類的新對象實例(實例化)。 創建對象的過程類似于[函數](/python-programming/function)的調用。 ```py >>> harry = Person() ``` 這將創建一個名為`harry`的新對象實例。 我們可以使用對象名稱前綴訪問對象的屬性。 屬性可以是數據或方法。 對象的方法是該類的相應函數。 這意味著,由于`Person.greet`是函數對象(類的屬性),因此`Person.greet`將是方法對象。 ```py class Person: "This is a person class" age = 10 def greet(self): print('Hello') # create a new object of Person class harry = Person() # Output: <function Person.greet> print(Person.greet) # Output: <bound method Person.greet of <__main__.Person object>> print(harry.greet) # Calling object's greet() method # Output: Hello harry.greet() ``` **輸出**: ```py <function Person.greet at 0x7fd288e4e160> <bound method Person.greet of <__main__.Person object at 0x7fd288e9fa30>> Hello ``` 您可能已經在類內的函數定義中注意到了`self`參數,但是我們將該方法簡單地稱為`harry.greet()`,而沒有任何[參數](/python-programming/function-argument)。 它仍然有效。 這是因為,只要對象調用其方法,該對象本身就會作為第一個參數傳遞。 因此,`harry.greet()`轉換為`Person.greet(harry)`。 通常,調用帶有 n 個參數列表的方法等同于調用帶有參數列表的函數,該參數列表是通過在第一個參數之前插入方法的對象而創建的。 由于這些原因,類中函數的第一個參數必須是對象本身。 通常將其稱為`self`。 可以使用其他名稱,但我們強烈建議您遵循約定。 現在,您必須熟悉類對象,實例對象,函數對象,方法對象及其區別。 * * * ## Python 中的構造器 以雙下劃線`__`開頭的類函數由于具有特殊含義而稱為特殊函數。 一個特別有趣的是`__init__()`函數。 每當實例化該類的新對象時,都會調用此特殊函數。 這種類型的函數在面向對象編程(OOP)中也稱為構造器。 我們通常使用它來初始化所有變量。 ```py class ComplexNumber: def __init__(self, r=0, i=0): self.real = r self.imag = i def get_data(self): print(f'{self.real}+{self.imag}j') # Create a new ComplexNumber object num1 = ComplexNumber(2, 3) # Call get_data() method # Output: 2+3j num1.get_data() # Create another ComplexNumber object # and create a new attribute 'attr' num2 = ComplexNumber(5) num2.attr = 10 # Output: (5, 0, 10) print((num2.real, num2.imag, num2.attr)) # but c1 object doesn't have attribute 'attr' # AttributeError: 'ComplexNumber' object has no attribute 'attr' print(num1.attr) ``` **輸出**: ```py 2+3j (5, 0, 10) Traceback (most recent call last): File "<string>", line 27, in <module> print(num1.attr) AttributeError: 'ComplexNumber' object has no attribute 'attr' ``` 在上面的示例中,我們定義了一個新類來表示復數。 它具有兩個函數,`__init__()`初始化變量(默認為零),`get_data()`正確顯示數字。 在上面的步驟中要注意的一件有趣的事情是,可以動態創建對象的屬性。 我們為對象`num2`創建了一個新屬性`attr`,并且也讀取了該屬性。 但這不會為對象`num1`創建該屬性。 * * * ## 刪除屬性和對象 可以使用`del`語句隨時刪除對象的任何屬性。 在 Python Shell 上嘗試以下操作以查看輸出。 ```py >>> num1 = ComplexNumber(2,3) >>> del num1.imag >>> num1.get_data() Traceback (most recent call last): ... AttributeError: 'ComplexNumber' object has no attribute 'imag' >>> del ComplexNumber.get_data >>> num1.get_data() Traceback (most recent call last): ... AttributeError: 'ComplexNumber' object has no attribute 'get_data' ``` 我們甚至可以使用`del`語句刪除對象本身。 ```py >>> c1 = ComplexNumber(1,3) >>> del c1 >>> c1 Traceback (most recent call last): ... NameError: name 'c1' is not defined ``` 實際上,它比這更復雜。 當我們執行`c1 = ComplexNumber(1,3)`時,會在內存中創建一個新的實例對象,并且名稱`c1`與之綁定。 在命令`del c1`上,將刪除此綁定,并從相應的名稱空間中刪除名稱`c1`。 但是,該對象繼續存在于內存中,如果沒有其他名稱綁定,則該對象隨后會自動銷毀。 在 Python 中這種對未引用對象的自動銷毀也稱為垃圾回收。 ![Deleting Object in Python](https://img.kancloud.cn/12/85/12856369e667c43c685cfd164e45bb50_480x231.png "Deleting Object in Python") 在 Python 中刪除對象會刪除名稱綁定
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看