zoukankan      html  css  js  c++  java
  • python魔法方法实现对象'+'操作符

    python对象重写__add__,__radd__方法即可实现'+'操作符

    demo:

     1 # coding=utf-8
     2 
     3 class Person(object):
     4     def __init__(self, age):
     5         self.age = age
     6     def __add__(self, other):
     7         return self.age + other
     8     def __radd__(self, other):
     9         return self.age + other
    10 
    11 print(Person(5) + Person(10))

    输出结果:

    15

    注意:

    如果 a 有 __add__ 方法, 而且返回值不是 NotImplemented, 调用a.__add__(b), 然后返回结果。
    如果 a 没有 __add__ 方法, 或者调用 __add__ 方法返回NotImplemented, 检查 b 有没有 __radd__ 方法, 如果有, 而且没有返回 NotImplemented, 调用 b.__radd__(a), 然后返回结果。
    如果 b 没有 __radd__ 方法, 或者调用 __radd__ 方法返回NotImplemented, 抛出 TypeError, 并在错误消息中指明操作数类型不支持。

  • 相关阅读:
    WEB
    Python
    Git
    JavaScript
    鸡汤
    面向对象
    Python
    Python
    MongoDB
    Oracle 11g 安装
  • 原文地址:https://www.cnblogs.com/reboot777/p/10384513.html
Copyright © 2011-2022 走看看