Python 類中的 self


在本教程中,我們將學習 Python 中的 self。如果您使用 Python,那麼您一定熟悉它。我們將瞭解一些關於它的有趣之處。

注意 - self 在 Python 中不是關鍵字。

讓我們從 Python 中 self 最常見的用法開始。

我們將在類中使用 self 來表示物件的例項。我們可以建立多個類的例項,並且每個例項都將具有不同的值。而 self 幫助我們在類例項中獲取這些屬性值。讓我們來看一個例子。

示例

# class
class Laptop:
   # init method
   def __init__(self, company, model):
      # self
      self.company = company
      self.model = model

我們將類的屬性定義為 self.[something]。因此,每當我們建立一個 的例項時,self 將引用一個不同的例項,我們從中訪問類屬性或方法。

現在,讓我們建立兩個 Laptop 類的例項,看看 self 如何工作

示例

演示

# class
class Laptop:
   # init method
   def __init__(self, company, model):
      # self
      self.company = company
      self.model = model
# creating instances for the class Laptop
laptop_one = Laptop('Lenovo', 'ideapad320')
laptop_two = Laptop('Dell', 'inspiron 7000')
# printing the properties of the instances
print(f"Laptop One: {laptop_one.company}")
print(f"Laptop Two: {laptop_two.company}")

輸出

如果您執行上述程式碼,則將得到以下結果。

Laptop One: Lenovo
Laptop Two: Dell

我們為同一個屬性得到了兩個不同的名稱。讓我們看看其背後的細節。

Python 在訪問其方法時預設會發送對例項的引用,而該引用被捕獲在 self 中。因此,對於每個例項,引用都是不同的。我們將獲得相應的例項屬性。

我們知道 self 不是 Python 的關鍵字。它更像是一個引數,在訪問例項的任何屬性或方法時,您不需要傳送它。

Python 將自動為您傳送對例項的引用。我們可以使用任何變數名來捕獲例項的引用。執行以下程式碼並檢視輸出。

示例

演示

import inspect
# class
class Laptop:
   # init method
   def __init__(other_than_self, company, model, colors):
      # self not really
      other_than_self.company = company
      other_than_self.model = model
      other_than_self.colors_available = colors
      # method
      def is_laptop_available(not_self_but_still_self, color):
         # return whether a laptop in specified color is available or not
         return color in not_self_but_still_self.colors_available
         # creating an instance to the class
         laptop = Laptop('Dell', 'inspiron 7000', ['Silver', 'Black'])
# invoking the is_laptop_available method withour color keyword
print("Available") if laptop.is_laptop_available('Silver') else print("Not available")
print("Available") if laptop.is_laptop_available('White') else print("Not available")

輸出

如果您執行上述程式碼,則將得到以下結果。

Available
Not available

我們將名稱 self 更改為 其他名稱。但是,它仍然像以前一樣工作。沒有區別。因此,self 不是關鍵字。此外,我們可以將 self 更改為我們喜歡的任何名稱。它更像是一個引數。

注意 - 最佳實踐是使用 self.。這是每個 Python 程式設計師都遵循的標準。

結論

如果您在本教程中有任何疑問,請在評論部分提出。

更新於:2020年7月11日

瀏覽量 1K+

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告