擅长:python、mysql、java
<p>从错误发生的地方来看,<code>reductor</code>不是{<cd2>},而是一个内置函数,这意味着错误发生在C代码中我们看不到回溯的地方。但我的猜测是,它试图获取一个不确定存在的方法,如果不存在,就准备捕捉<code>AttributeError</code>。相反,它调用<code>.get</code>,后者返回<code>None</code>,没有错误,因此它尝试调用该方法。在</p>
<p>其行为正确:</p>
<pre><code>class DotDict(dict):
"""dot.notation access to dictionary attributes"""
def __getattr__(self, item):
try:
return self[item]
except KeyError as e:
raise AttributeError from e
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
a = DotDict(x=1, b=2)
print(deepcopy(a))
</code></pre>
<p>我知道这与您的原始类的行为不同,而且您将无法将<code>.</code>用于可选键,但是我认为有必要避免这样的错误,因为外部代码希望您的类以可预测的方式运行。在</p>
<p>编辑:以下是实现deepcopy并保留原始<code>__getattr__</code>的方法:</p>
^{pr2}$
<p>测试:</p>
<pre><code>dd = DotDict(x=1, b=2, nested=DotDict(y=3))
copied = deepcopy(dd)
print(copied)
assert copied == dd
assert copied.nested == dd.nested
assert copied.nested is not dd.nested
assert type(dd) is type(copied) is type(dd.nested) is type(copied.nested) is DotDict
</code></pre>