带 modulus/percent 符号的字符串格式

string formatting with modulus/percent sign

在调用任一函数时使用取模函数的字符串格式设置是否有问题

StringOperand % TupleOperand

StringOperand % DictionaryOperand

还是只是随意使用 % 作为字符串格式化函数?

我猜测字符串格式化运算符不是对模块化算术的调用,如下所示:

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

打印:1 2 3,但是

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

returns 类型错误:格式 str

的参数不足

这是operator overloading。您所说的是内置语言,但您可以自己重载方法。例如,通过 __add__ 方法在 python 中重载 + 运算符:

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)

+ 将连接而不是求和。 在这种情况下 x+y 的结果是 54