Python Magic Methods - Python 中的魔法方法

优质
小牛编辑
127浏览
2023-12-01

Python 中的对象都有诸如 __init__() 这样的方法,它们都有各自特定的用途,却
无法直接被调用。虽然无法被直接调用,实际上你却经常在使用这些方法,比如创建对象实例式
就调用了 __new__()__init__ 方法。那么这些魔法方法还有那些其它的有趣用法呢?

操作符重载

Python 中的操作符运算实际上都是在隐式地调用这些魔法方法,如果你重写了对应的魔法方法,
就能修改操作符的运算规则。比如,逻辑或操作符 | 对应了魔法方法 __ror__
因此我们可以重载 __ror__ 来实现类似 Shell 中的管道:

  1. class Pipe(object):
  2. def __init__(self, func):
  3. self.func = func
  4. def __ror__(self, other):
  5. def generator():
  6. for obj in other:
  7. if obj is not None:
  8. yield self.func(obj)
  9. return generator()
  10. @Pipe
  11. def even_filter(num):
  12. return num if num % 2 == 0 else None
  13. @Pipe
  14. def multiply_by_three(num):
  15. return num*3
  16. @Pipe
  17. def convert_to_string(num):
  18. return 'The Number: %s' % num
  19. @Pipe
  20. def echo(item):
  21. print item
  22. return item
  23. def force(sqs):
  24. for item in sqs: pass
  25. nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  26. force(nums | even_filter | multiply_by_three | convert_to_string | echo)

(代码出自酷壳网友

这里有张详细的对照表:

  1. Binary Operators
  2. Operator Method
  3. + object.__add__(self, other)
  4. - object.__sub__(self, other)
  5. * object.__mul__(self, other)
  6. // object.__floordiv__(self, other)
  7. / object.__div__(self, other)
  8. % object.__mod__(self, other)
  9. ** object.__pow__(self, other[, modulo])
  10. << object.__lshift__(self, other)
  11. >> object.__rshift__(self, other)
  12. & object.__and__(self, other)
  13. ^ object.__xor__(self, other)
  14. | object.__or__(self, other)
  15. Extended Assignments
  16. Operator Method
  17. += object.__iadd__(self, other)
  18. -= object.__isub__(self, other)
  19. *= object.__imul__(self, other)
  20. /= object.__idiv__(self, other)
  21. //= object.__ifloordiv__(self, other)
  22. %= object.__imod__(self, other)
  23. **= object.__ipow__(self, other[, modulo])
  24. <<= object.__ilshift__(self, other)
  25. >>= object.__irshift__(self, other)
  26. &= object.__iand__(self, other)
  27. ^= object.__ixor__(self, other)
  28. |= object.__ior__(self, other)
  29. Unary Operators
  30. Operator Method
  31. - object.__neg__(self)
  32. + object.__pos__(self)
  33. abs() object.__abs__(self)
  34. ~ object.__invert__(self)
  35. complex() object.__complex__(self)
  36. int() object.__int__(self)
  37. long() object.__long__(self)
  38. float() object.__float__(self)
  39. oct() object.__oct__(self)
  40. hex() object.__hex__(self
  41. Comparison Operators
  42. Operator Method
  43. < object.__lt__(self, other)
  44. <= object.__le__(self, other)
  45. == object.__eq__(self, other)
  46. != object.__ne__(self, other)
  47. >= object.__ge__(self, other)
  48. > object.__gt__(self, other)

参考:Magic Methods and Operator Overloading