Decimal()对象的Python deepcopy()

swi*_*_on 0 python class decimal deep-copy

我正在努力使用deepcopy()一个包含Decimal值的类.所以我尝试自己深度复制一个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
Run Code Online (Sandbox Code Playgroud)

类复制但小数引用保持不变.

Mar*_*ers 5

Python的copy模块不会生成不可变对象的副本,效率非常低.decimal.Decimal()对象是不可变的,因此它们只返回self复制操作:

>>> from decimal import Decimal
>>> d = Decimal()
>>> d.__copy__() is d
True
>>> d.__deepcopy__({}) is d
True
Run Code Online (Sandbox Code Playgroud)

请参阅decimal模块文档:

十进制数是不可变的.

因为它们是不可变的,所以创建副本没有意义 ; 无处不在,你可以使用复制,你可以放心地使用原,但没有就永远无法发散两个完全一致的对象浪费内存.