Python Decimal() 对象的 deepcopy()

Python deepcopy() of a Decimal() object

我正在努力 deepcopy() 一个包含 Decimal 值的 class。所以我尝试自己深度复制一个 Decimal 对象,但也失败了。我在这里误解了什么?

from copy import deepcopy
from decimal import Decimal

## Deepcopy an array ##
a = [1,2,3,4]
b = deepcopy(a)
a is b
# False

## Deep copy a Decimal ##
a = Decimal('0.123')
b = deepcopy(a)
a is b
# True

## Deepcopy a class containing a Decimal ##
class A(object):
    def __init__(self, dec):
        self.myDecimal = Decimal(dec)

a = A('0.123')
b = deepcopy(a)
a is b
# False

a.myDecimal is b.myDecimal
# True

class 副本,但十进制参考保持不变。

Python 的 copy 模块不会生成不可变对象的副本,那样效率非常低。 decimal.Decimal() 对象是不可变的,所以它们只是 return self 用于复制操作:

>>> from decimal import Decimal
>>> d = Decimal()
>>> d.__copy__() is d
True
>>> d.__deepcopy__({}) is d
True

查看 decimal module documentation:

A decimal number is immutable.

因为它们是不可变的,所以创建副本没有意义;在任何可以使用副本的地方,也可以安全地使用原始 ,但不会将内存浪费在两个永远不会分歧的完全相同的对象上。