开发者

str.format() problem

So I made this class that outputs '{0}' when x=0 or '{1}' for every other value of x.

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. 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", i.e., the string form of whatever you passed to offset().

To change that intrinsic value you might override __new__, e.g.:

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜