在比较的魔法方法中,咱们讨论了魔法方法其实就是重载了操做符,例如>、<、==等。而这里,咱们继续讨论有关于数值的魔法方法。python
__pos__(self)函数
实现一个取正数的操做(好比 +some_object ,python调用__pos__函数)spa
__neg__(self).net
实现一个取负数的操做(好比 -some_object )3d
__abs__(self)code
实现一个内建的abs()函数的行为blog
__invert__(self)get
实现一个取反操做符(~操做符)的行为。it
__round__(self, n)io
实现一个内建的round()函数的行为。 n 是待取整的十进制数.(貌似在2.7或其余新版本中废弃)
__floor__(self)
实现math.floor()的函数行为,好比, 把数字下取整到最近的整数.(貌似在2.7或其余新版本中废弃)
__ceil__(self)
实现math.ceil()的函数行为,好比, 把数字上取整到最近的整数.(貌似在2.7或其余新版本中废弃)
__trunc__(self)
实现math.trunc()的函数行为,好比, 把数字截断而获得整数.
class Foo(str): def __new__(cls, x, *args, **kwargs): return super(Foo, cls).__new__(cls, x) def __init__(self, x): self.x = x def __pos__(self): return '+' + self.x def __neg__(self): return '-' + self.x def __abs__(self): return 'abs:' + self.x def __invert__(self): return 'invert:' + self.x a = Foo('scolia') print +a print -a print ~a
__add__(self, other)
实现一个加法.
__sub__(self, other)
实现一个减法.
__mul__(self, other)
实现一个乘法.
__floordiv__(self, other)
实现一个“//”操做符产生的整除操做
__div__(self, other)
实现一个“/”操做符表明的除法操做.(由于Python 3里面的division默认变成了true division,__div__在Python3中不存在了)
__truediv__(self, other)
实现真实除法,注意,只有当你from __future__ import division时才会有效。
__mod__(self, other)
实现一个“%”操做符表明的取模操做.
__divmod__(self, other)
实现一个内建函数divmod()
__pow__
实现一个指数操做(“**”操做符)的行为
__lshift__(self, other)
实现一个位左移操做(<<)的功能
__rshift__(self, other)
实现一个位右移操做(>>)的功能.
__and__(self, other)
实现一个按位进行与操做(&)的行为.
__or__(self, other)
实现一个按位进行或操做(|)的行为.
__xor__(self, other)
实现一个异或操做(^)的行为
class Foo(str): def __new__(cls, x, *args, **kwargs): return super(Foo, cls).__new__(cls, x) def __init__(self, x): self.x = x def __add__(self, other): return self.x + '+' + other.x def __sub__(self, other): return self.x + '-' + other.x def __mul__(self, other): return self.x + '*' + other.x def __floordiv__(self, other): return self.x + '//' + other.x def __div__(self, other): return self.x + '/' + other.x def __truediv__(self, other): return self.x + 't/' + other.x def __mod__(self, other): return self.x + '%' + other.x def __divmod__(self, other): return self.x + 'divmod' + other.x def __pow__(self, power, modulo=None): return self.x + '**' + str(power) def __lshift__(self, other): return self.x + '<<' + other.x def __rshift__(self, other): return self.x + '>>' + other.x def __and__(self, other): return self.x + '&' + other.x def __or__(self, other): return self.x + '|' + other.x def __xor__(self, other): return self.x + '^' + other.x a = Foo('scolia') b = Foo('good') print a + b print a - b print a * b print a // b print a / b print a % b print divmod(a, b) print a ** b print a << b print a >> b print a & b print a | b print a ^ b
from __future__ import division ....... print a / b
欢迎你们交流
参考资料:戳这里