我们知道:
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)
