简体   繁体   English

str.format()问题

[英]str.format() problem

So I made this class that outputs '{0}' when x=0 or '{1}' for every other value of x. 所以我创建了这个类,当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

I want to do this: 我想做这个:
offset(1).format('first', 'next')
but it will only return the number I give for x as a string. 但它只返回我给x作为字符串的数字。 What am I doing wrong? 我究竟做错了什么?

Your subclass of str does not override format , so when you call format on one of its instances it just uses the one inherited from str which uses self 's "intrinsic value as str ", ie, the string form of whatever you passed to offset() . 你的str子类没有覆盖format ,所以当你在其中一个实例上调用format时,它只使用从str继承的那个,它使用self的“内在值为str ”,即你传递给offset()的任何字符串形式offset()

To change that intrinsic value you might override __new__ , eg: 要更改该内在值,您可以覆盖__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')

emits 发射

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

Note there's no need to also override __repr__ if, by overriding __new__ , you're already ensuring that the instance's intrinsic value as str is the format you desire. 注意,如果通过覆盖__new__ ,您已经确保实例的内部值为str是您想要的格式,则无需覆盖__repr__

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

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