gpt4 book ai didi

class - Python更新继承的类级别字典

转载 作者:行者123 更新时间:2023-12-03 00:11:28 25 4
gpt4 key购买 nike

我正在寻找一种干净、简单的方法来更新从基类继承的类级字典。例如:

class Foo(object):
adict = {'a' : 1}

class Bar(Foo):
adict.update({'b' : 2}) # this errors out since it can't find adict

这样:

Foo.adict == {'a' : 1}
Bar.adict == {'a' : 1, 'b' : 2}

我不想在这里使用实例,如果可能的话也不使用类方法。

最佳答案

请注意,即使这有效,您也将更新同一字典而不是创建新字典(因此 Foo.adict is Bar.adictFoo.adict == Bar.adict )。

无论如何,最简单的方法是显式引用父类的字典(并复制它,见上文):

class Bar(Foo):
adict = dict(Foo.adict)
adict.update({'b': 2})

关于class - Python更新继承的类级别字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8647370/

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