避免在 Python 中的实例之间共享类数据
pythonserver side programmingprogramming更新于 2025/9/4 23:40:17
当我们在 Python 中实例化一个类时,它的所有变量和函数也会被继承到新实例化的类中。但有时我们不希望子类继承父类的某些变量。在本文中,我们将探讨两种方法来实现这一点。
实例化示例
在下面的例子中,我们展示了变量是如何从给定的类中实例化的,以及如何在所有实例化的类之间共享变量。
class MyClass:
listA= []
# 实例化两个类
x = MyClass()
y = MyClass()
# 操作两个类
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)
# 打印结果
print("Instance X: ",x.listA)
print("Instance Y: ",y.listA)
输出
运行上述代码得到以下结果 −
Instance X: [10, 20, 30, 40] Instance Y: [10, 20, 30, 40]
使用 __inti__ 的私有类变量
我们可以使用 I need a 方法将类中的变量设为私有。实例化父类时,这些变量不会在类之间共享。
示例
class MyClass:
def __init__(self):
self.listA = []
# 实例化两个类
x = MyClass()
y = MyClass()
# 操作两个类
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)
# 打印结果
print("Instance X: ",x.listA)
print("Instance Y: ",y.listA)
输出
运行上述代码得到以下结果 −
Instance X: [10, 30] Instance Y: [20, 40]
通过在类外声明变量
在这种方法中,我们将在类外重新声明变量。因为变量再次被初始化,所以不会在实例化的类之间共享。
示例
class MyClass:
listA = []
# 实例化两个类
x = MyClass()
y = MyClass()
x.listA = []
y.listA = []
# 操作两个类
x.listA.append(10)
y.listA.append(20)
x.listA.append(30)
y.listA.append(40)
# 打印结果
print("Instance X: ",x.listA)
print("Instance Y: ",y.listA)
Output
输出
运行上述代码得到以下结果 −
Instance X: [10, 30] Instance Y: [20, 40]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

