避免 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]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP