代码如下
class Point:
dic = {}
def __init__(self, x=0):
self.dic[x] = x
pt1 = Point(1)
print(pt1.dic)
pt2 = Point(2)
print(pt2.dic)
他的打印结果是
{1: 1}
{1: 1, 2: 2}
这里pt2对象为何受到了pt1对象的影响?
代码如下
class Point:
dic = {}
def __init__(self, x=0):
self.dic[x] = x
pt1 = Point(1)
print(pt1.dic)
pt2 = Point(2)
print(pt2.dic)
他的打印结果是
{1: 1}
{1: 1, 2: 2}
这里pt2对象为何受到了pt1对象的影响?
4 回答4.4k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
1 回答3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
1 回答4.5k 阅读✓ 已解决
1 回答3.8k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
这时 Python 类变量的特性:类及其所有实例共享类变量。
你的两个实例 pt1 和 pt2 访问的 dic 都是同一个 dic。在实际使用中,应该避免这样做,尤其该变量为 可变对象 时(如 list、dict)。
针对你的场景,你完全可以这样做: