打印没有标签 "Decimal" 的 Decimals 元组

Print tuple of Decimals without the label "Decimal"

我有一个Vectorclass如下:

class Vector(object):

    def __init__(self, coordinates):
        self.coordinates = tuple([Decimal(x) for x in coordinates])

    def __str__(self):
        return 'Vector: {}'.format(self.coordinates)

如果我运行下面的代码...

v1 = Vector([1,1])
print v1

...我得到

Vector: (Decimal('1'), Decimal('1'))

如何去掉标签'Decimal'? 输出应如下所示:

Vector: (1, 1)

只需调用str函数:

import decimal
d = decimal.Decimal(10)
d
Decimal('10')
str(d)
'10'

对于您的代码:

def __str__(self):
    return 'Vector: {}'.format(map(str, self.coordinates))

在小数点前后加上 str() 有效:

from __future__ import print_function
from decimal import Decimal

class Vector(object):

    def __init__(self, coordinates):
        self.coordinates = tuple([Decimal(x) for x in coordinates])

    def __str__(self):
        return 'Vector: ({})'.format(', '.join(str(x) for x in self.coordinates))

v1 = Vector([1,1])
print(v1)

输出:

Vector: (1, 1)