在 python 中的 class 函数中使用 round 根本不会四舍五入

Using round within class function in python doesn't round at all

我正在进行温度转换,并希望将转换四舍五入为指定的十进制长度。程序执行没有错误,但转换最终没有舍入。

def to(self, unit, dp=None):  # convert self.celcius to temperature measure
    if unit == 'C':
        self.number = self.celcius()
    elif unit == 'F':
        self.number = (9 / 5 * self.celcius()) + 32
    elif unit == 'K':
        self.number = self.celcius() + 273.15
    else:
        raise Exception("Unit not recognised")
    if dp: number = round(self.number, dp)
    return f"{self.number}{unit}"

temp_1 = Temperature(32, 'C')
temp_2 = Temperature(100, 'F')
temp_3 = Temperature(324, 'K')

# Convert them
print(temp_1.to('F')) 
print(temp_2.to('K', 3)) 
print(temp_3.to('C', 1)) 

如果问题需要,我可以提供更多代码 if dp: number = round(self.number, dp) 因为小数没有被缩短。

if dp:
  number = round(self.number, dp)

在这里,我们创建了一个名为 number 的新局部变量,然后不再使用它。您可能打算设置 self.number.

if dp:
  self.number = round(self.number, dp)