子类string.Formatter [英] subclass string.Formatter

查看:89
本文介绍了子类string.Formatter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此处加上备注:如何定义新的字符串格式器,我尝试对string.Formatter进行子类化.这是我所做的.不幸的是,我似乎在此过程中将其破坏了

Following a remark here: How to define a new string formatter, I tried subclassing string.Formatter. Here is what I've done. Unfortunately I seem to have broken it in the process

import string
from math import floor, log10

class CustFormatter(string.Formatter):
    "Defines special formatting"
    def __init__(self):
        super(CustFormatter, self).__init__()

    def powerise10(self, x):
        if x == 0: return 0, 0
        Neg = x < 0
        if Neg: x = -x
        a = 1.0 * x / 10**(floor(log10(x)))
        b = int(floor(log10(x)))
        if Neg: a = -a
        return a, b

    def eng(self, x):
        a, b = self.powerise10(x)
        if -3 < b < 3: return "%.4g" % x
        a = a * 10**(b%3)
        b = b - b%3
        return "%.4g*10^%s" % (a, b)

    def format_field(self, value, format_string):
      # handle an invalid format
      if format_string == "i":
          return self.eng(value)
      else:
          return super(CustFormatter,self).format_field(value, format_string)

fmt = CustFormatter()
print('{}'.format(0.055412))
print(fmt.format("{0:i} ", 55654654231654))
print(fmt.format("{} ", 0.00254641))

就像在最后一行中一样,我没有按位置引用变量,所以得到了KeyError.显然,它期望在原始类中是可选的键,但是我不明白为什么,而且我不确定自己做错了什么.

As if as in the last line, I don't refer to the variables by position, I get a KeyError. It is obviously expecting a key which is optional in the original class but I don't understand why and I am not sure what I've done wrong.

推荐答案

str.format

str.format does auto numbering, while string.Formatter does not.

修改__init__并覆盖get_value即可解决问题.

Modifying __init__ and overriding get_value will do the trick.

def __init__(self):
    super(CustFormatter, self).__init__()
    self.last_number = 0

def get_value(self, key, args, kwargs):
    if key == '':
        key = self.last_number
        self.last_number += 1
    return super(CustFormatter, self).get_value(key, args, kwargs)

顺便说一句,上面的代码并不严格模仿str.format行为. str.format抱怨我们是否将自动编号与手动编号混合使用,但是上面没有.

BTW, above code does not strictly mimic str.format behavior. str.format complains if we mix auto numbering with manual number, but above does not.

>>> '{} {1}'.format(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot switch from automatic field numbering to manual field specification
>>> '{0} {}'.format(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot switch from manual field specification to automatic field numbering

这篇关于子类string.Formatter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆