2

Is there something happening when string formatting that uses the modulus function while calling either

StringOperand % TupleOperand or

StringOperand % DictionaryOperand

Or is it just an arbitrary use of % for the string formatting function?

I'm guessing that the string formatting operator is not a call to modular arithmetic as the following:

tuple = (1,2,3)
print '%d %d %d'%tuple

prints: 1 2 3, but

print '%d %d %d %d'%tuple

returns TypeError: not enough args for format str

MmmHmm
  • 3,435
  • 2
  • 27
  • 49
  • 3
    This is called *operator overloading* and is common in python. A class can implement an operator to mean anything it likes by implementing a special method, in this case `__mod__()`. For example, try `print "hello" * 3`. See also https://docs.python.org/2/library/operator.html – cdarke Apr 06 '16 at 07:50

1 Answers1

3

This is operator overloading. What you are talking about is language build-in, but you may overload methods on your own. Eg overload + operator that is decorated in python by __add__ method:

class YourMath(object):
    def __init__(self, param):
        self.param = param

    def __add__(self, x):
        return int(str(self.param) + str(x.param)) # concatenation 


x = YourMath(5)
y = YourMath(4)

+ will concatenate instead of sum up. Result of x+y in this case is 54.

Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192