python - 有没有办法覆盖 __format__ 方法

标签 python string

我们知道:

str.format('{:+>10}', 'sometext')

将返回:

'++sometext'

或: '{:+>10}'.format('sometext') 将返回 '++sometext' 我的问题是,是否可以覆盖类实例的 format 方法……我试过这个:

class A:
    def __format__(self, spec):
        return spec.format(self)

然后实例化它:

a = A()
a.__format__('{:+>20}')

返回 '+>20' 这怎么会发生... 先谢谢

最佳答案

def __format__(self,spec): 中,spec 是格式字符串本身。如果要使用该规范格式化类,则需要以某种方式将其指定为类实例内容的格式,例如:

class Value:

    def __init__(self,value):
        self.value = value

    def __format__(self,fmt):                # fmt='03' from below.
        return f'Value({self.value:{fmt}})'  # f'Value({self.value:03})' is evaluated.

v = Value(5)
print(f'{v:03}')         # Python 3.6+
print('{:04}'.format(v)) # Python <3.6

输出:

Value(005)
Value(0005)

关于python - 有没有办法覆盖 __format__ 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54357419/

相关文章:

带参数的 Python 描述符?

java - number.charAt() 也适用于十六进制吗?

javascript - 以正确的方式使用javascript将动态表单添加到django formset

python - jinja2如何在日期时间中删除微秒

PHP Heredoc 字符串规则

python - Str split 并爆炸

C++函数从字符串中误读字符

javascript - 将字符串数组更改为字符串数组

python - 连接字符串时的括号注入(inject)

python - 对 2^30 个 32 位整数进行排序。最佳解决方案