gpt4 book ai didi

具有字典变异的 Python 继承

转载 作者:行者123 更新时间:2023-11-28 21:47:09 25 4
gpt4 key购买 nike

我很好奇在字典突变的情况下继承是如何工作的,我一直认为每个新实例都会重新创建继承的类。

class A(object):
test = {"B": 0}

def change_test(self, index):
self.test["B"] += index

def __init__(self, **kwargs):
self.change_test(self.index)
super(A, self).__init__(**kwargs)


class B(A):
index = 1
def print_test(self):
print self.test


class C(A):
index = 2
def print_test(self):
print self.test

b = B()
b.print_test()

c = C()
c.print_test()

为什么返回 {'B': 1} {'B': 3} 而不是 {'B': 1} {'B': 2}?

最佳答案

test 类变量在 A 及其子实例之间共享。

print A.test is B.test # True
print B.test is C.test # True

最初,test{"B": 0}。当您初始化 b 时,A 中的 change_test 被调用,因为 B 继承了 __init__ A. 所以现在 test{"B": 1}。之后,您初始化 c,这将导致对 change_test 的另一个调用,其中 index 为 2。现在 test{"B": 3} 因为 1 + 2 = 3。

关于具有字典变异的 Python 继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36921137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com