str.format()问题

3

所以我创建了这个类,当x=0时输出'{0}',对于x的任何其他值输出'{1}'。

class offset(str):  
    def __init__(self,x):  
        self.x=x  
    def__repr__(self):
        return repr(str({int(bool(self.x))}))
    def end(self,end_of_loop):
    #ignore this def it works fine
        if self.x==end_of_loop:
            return '{2}'
        else:
            return self

我想执行以下操作:
offset(1).format('first', 'next')
但它只会返回我提供的数字作为字符串。那我做错了什么?

1个回答

4
您的str子类没有覆盖format,因此当您在其实例上调用format时,它只使用从str继承的一个,该方法使用self的“作为str的固有值”,即您传递给offset()的字符串形式。
要更改该固有值,您可以覆盖__new__,例如:
class offset(str):
    def __init__(self, x):
        self.x = x
    def __new__(cls, x):
        return str.__new__(cls, '{' + str(int(bool(x))) + '}')

for i in (0, 1):
  x = offset(i)
  print x
  print repr(x)
  print x.format('first', 'next')

发射

{0}
'{0}'
first
{1}
'{1}'
next

请注意,如果通过覆盖__new__方法已经确保实例的内在值作为str格式符合您的要求,则无需再覆盖__repr__方法。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接