3

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.