📜  Python|避免在实例之间共享类数据

📅  最后修改于: 2022-05-13 01:54:54.559000             🧑  作者: Mango

Python|避免在实例之间共享类数据

类属性属于类本身,它们将由所有实例共享,因此包含每个实例的相同值。为了便于阅读,此类属性通常在类主体部分中定义。

假设我们有以下代码片段:

Python3
# Python code to demonstrate
# the working of the sharing
# of data variables
 
# Creating a class
class Geek_Class:
    geek = []
 
x = Geek_Class()
y = Geek_Class()
 
# Appending the values
x.geek.append(1)
y.geek.append(2)
x.geek.append(3)
y.geek.append(4)
 
# Printing the values for x and y
print(x.geek)
print(y.geek)


Python3
# Python code to demonstrate
# the working of the sharing
# of data variables
 
# Creating a class inside __init__
class Geek_Class:
    def __init__(self):
        self.geek = []
 
x = Geek_Class()
y = Geek_Class()
 
# Appending the values
x.geek.append(1)
y.geek.append(2)
x.geek.append(3)
y.geek.append(4)
 
# Printing the values for x and y
print(x.geek)
print(y.geek)


Python3
# Python code to demonstrate
# the working of the sharing
# of data variables
 
# Creating a class
class Geek_Class:
    geek =[]
 
x = Geek_Class()
y = Geek_Class()
 
# Creating the new lists
x.geek = []
y.geek = []
 
# Appending the values
x.geek.append(1)
y.geek.append(2)
x.geek.append(3)
y.geek.append(4)
 
# Printing the values for x and y
print(x.geek)
print(y.geek)


输出:
[1, 2, 3, 4]
[1, 2, 3, 4]

它为 x 打印 [1, 2, 3, 4],为 y 打印 [1, 2, 3, 4]。假设我们想要的输出是 x 的 [1, 3] 和 y 的 [2, 4]。我们可以通过以下方式得到想要的输出:

方法 #1 :通过在 __init__ 中声明它们
在类声明中声明变量使它们成为类成员而不是实例成员。在 __init__ 方法中声明它们可确保在对象的每个新实例旁边创建成员的新实例,这正是我们所需要的。

Python3

# Python code to demonstrate
# the working of the sharing
# of data variables
 
# Creating a class inside __init__
class Geek_Class:
    def __init__(self):
        self.geek = []
 
x = Geek_Class()
y = Geek_Class()
 
# Appending the values
x.geek.append(1)
y.geek.append(2)
x.geek.append(3)
y.geek.append(4)
 
# Printing the values for x and y
print(x.geek)
print(y.geek)
输出:
[1, 3]
[2, 4]

在原始代码中,实例化后没有为列表属性赋值;所以它仍然是一个类属性。在 __init__ 中定义列表是有效的,因为 __init__ 在实例化之后被调用。方法#2:通过创建新列表并将值存储在其中。

Python3

# Python code to demonstrate
# the working of the sharing
# of data variables
 
# Creating a class
class Geek_Class:
    geek =[]
 
x = Geek_Class()
y = Geek_Class()
 
# Creating the new lists
x.geek = []
y.geek = []
 
# Appending the values
x.geek.append(1)
y.geek.append(2)
x.geek.append(3)
y.geek.append(4)
 
# Printing the values for x and y
print(x.geek)
print(y.geek)
输出:
[1, 3]
[2, 4]