避免在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("实例X: ",x.listA)
print("实例Y: ",y.listA)输出结果
运行上面的代码给我们以下结果-
实例X: [10, 20, 30, 40] 实例Y: [10, 20, 30, 40]
带有__inti__的私有类变量
我们可以使用我需要的一种方法来将类中的变量设为私有。当实例化父类时,这些变量将不会在所有类之间共享。
示例
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("实例X: ",x.listA)
print("实例Y: ",y.listA)输出结果
运行上面的代码给我们以下结果-
实例X: [10, 30] 实例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("实例X: ",x.listA)
print("实例Y: ",y.listA)
Output输出结果
运行上面的代码给我们以下结果-
实例X: [10, 30] 实例Y: [20, 40]