繁体   English   中英

str.format()问题

[英]str.format() problem

所以我创建了这个类,当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')
但它只返回我给x作为字符串的数字。 我究竟做错了什么?

你的str子类没有覆盖format ,所以当你在其中一个实例上调用format时,它只使用从str继承的那个,它使用self的“内在值为str ”,即你传递给offset()的任何字符串形式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__

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM