Str.format () problem

So, I made this class that outputs '{0}' when x = 0 or '{1}' for any 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 that I pass for x as a string. What am I doing wrong?

+3
source share
1 answer

Your subclass strdoes not override format, so when you call formatin one of its instances, it just uses one inherited from strthat uses the self"internal value as str", i.e. the string form of what you passed offset().

To change this internal value, you can override __new__, for example:

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

, __repr__, , __new__, , str .

+4

Source: https://habr.com/ru/post/1726550/


All Articles