% string formatting - what special method is used for %d?

Ian Kelly ian.g.kelly at gmail.com
Sun Dec 11 02:21:18 EST 2016


On Sat, Dec 10, 2016 at 11:40 PM, Veek M <vek.m1234 at gmail.com> wrote:
> Well take a look at this:
> ###########################################
> #!/usr/bin/python
>
> class Foo(int):
>     def __init__(self, value):
>         self.value = value
>
>     def __str__(self):
>         print '__str__'
>         return str(self.value)
>
>     def __int__(self):
>         print '__int__'
>         return self.value + 1
>
>
> #'%s' % Foo(10) # %s is mapped to __str__
> '%d' % Foo(20)
> ###########################################
>
> here, '__str__' prints because when you do:
> '%s' % x
> the __str__ method is invoked. So internally %s invokes __str__
> independent of print.
>
> However the next line doesn't trigger any similar invocation with
> __int__ or__str__? (but int(Foo(10)) would invoked __int__)

This is probably because Foo inherits from int. Foo(20) is already an
int so there is no conversion to be done; Python simply uses the int
value and ignores the __int__ method in this case.

> Is there a way to trigger special methods using %d etc OR is this
> restricted to %s and why?

For an object that is already an int, probably not.

However you may want to revisit your decision to make Foo inherit from
int and question whether that is really sensible if you're also
wanting to override the __int__ method. What does that mean if
something is an int but also provides a method to convert to int? It's
a contradiction.



More information about the Python-list mailing list