避免 Python 中例項之間共享類資料


當我們在 Python 中例項化一個類時,其所有變數和函式也會繼承到新的例項化類中。但是,在某些情況下,我們可能不希望父類的一些變數被子類繼承。在本文中,我們將探討兩種實現此目的的方法。

例項化示例

在下面的示例中,我們展示了變數是如何從給定類中繼承的,以及變數如何在所有例項化類之間共享。

 現場演示

class MyClass:
   listA= []

# Instantiate Both the classes
x = MyClass()
y = MyClass()

# Manipulate both the classes
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)

# Print Results
print("Instance X: ",x.listA)
print("Instance Y: ",y.listA)

輸出

執行以上程式碼將得到以下結果:

Instance X: [10, 20, 30, 40]
Instance Y: [10, 20, 30, 40]

使用 __init__ 的私有類變數

我們可以使用一種方法將類中的變數設為私有。當例項化父類時,這些變數不會在類之間共享。

示例

 現場演示

class MyClass:
   def __init__(self):
      self.listA = []

# Instantiate Both the classes
x = MyClass()
y = MyClass()

# Manipulate both the classes
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)

# Print Results
print("Instance X: ",x.listA)
print("Instance Y: ",y.listA)

輸出

執行以上程式碼將得到以下結果:

Instance X: [10, 30]
Instance Y: [20, 40]

透過在類外部宣告變數

在這種方法中,我們將在類外部重新宣告變數。由於變數被再次初始化,因此不會在例項化類之間共享。

示例

 現場演示

class MyClass:
   listA = []

# Instantiate Both the classes
x = MyClass()
y = MyClass()

x.listA = []
y.listA = []
# Manipulate both the classes
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)

# Print Results
print("Instance X: ",x.listA)
print("Instance Y: ",y.listA)
Output

輸出

執行以上程式碼將得到以下結果:

Instance X: [10, 30]
Instance Y: [20, 40]

更新於: 2020-07-22

89 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.