Brian 的答案(自定义函数)通常是正确且最简单的做法。
但如果您真的想用(非标准)'%' 运算符定义数字类型,就像台式计算器那样,那么 'X % Y' 表示 X * Y / 100.0 , 然后从 Python 2.6 开始你可以重新定义the mod() operator:
import numbers
class MyNumberClasswithPct(numbers.Real):
def __mod__(self,other):
"""Override the builtin % to give X * Y / 100.0 """
return (self * other)/ 100.0
# Gotta define the other 21 numeric methods...
def __mul__(self,other):
return self * other # ... which should invoke other.__rmul__(self)
#...
如果您曾经在 MyNumberClasswithPct 与普通整数或浮点数的混合中使用“%”运算符,这可能会很危险。
这段代码的另一个乏味之处在于您还必须定义 Integral 或 Real 的所有 21 种其他方法,以避免在实例化它时出现以下烦人且晦涩的 TypeError
("Can't instantiate abstract class MyNumberClasswithPct with abstract methods __abs__, __add__, __div__, __eq__, __float__, __floordiv__, __le__, __lt__, __mul__, __neg__, __pos__, __pow__, __radd__, __rdiv__, __rfloordiv__, __rmod__, __rmul__, __rpow__, __rtruediv__, __truediv__, __trunc__")