使用class属性作为参数使用f字符串进行浮点格式化

问题描述

有可能做这样的事情吗?

class P():
    def __init__(self):
        self.digits = 5
        self.pi = f"{np.pi:eval(self.digits)f}"

test = test()
test.pi

我知道f"{np.pi:5.f}"可以工作,但是可以使用类的属性来做到这一点吗?喜欢以动态方式?不需要使用eval(),重要的部分是是否可以以某种方式使用self.digits

解决方法

您可以将格式嵌套在格式说明符中

以您的示例为例,并修复了一些问题(缺少导入,不必要的numpy,类名不匹配,打印变量而不是仅访问变量,在数字前加点以限制小数位):

import math

class Test():
    def __init__(self):
        self.digits = 5
        self.pi = f"{math.pi:.{self.digits}f}"

test = Test()
print(test.pi)

输出:

$ python3 t.py 
3.14159