【问题标题】:In an operation between two objects in python whose overloading of the operation as priority?在 python 中两个对象之间的操作中,其操作的重载为优先级?
【发布时间】:2014-04-26 01:44:51
【问题描述】:

例如,如果我在两个类中定义了__add____radd__,并且我将这两个对象相加,python 将使用哪个操作定义?

【问题讨论】:

  • 左边的操作数优先。

标签: python class operator-overloading


【解决方案1】:

如果左右手对象不相关,则左侧对象获胜。但是,如果其中一个对象是另一个对象的子类,则无论是左手对象还是右手对象,子类都会胜出。

>>> class Foo(object):
...   def __add__(self, rhs):
...     print('foo.add')
...   def __radd__(self, rhs):
...     print('foo.radd')
... 
>>> class Bar(Foo):
...   def __add__(self,rhs):
...     print('bar.add')
...   def __radd__(self, rhs):
...     print('bar.radd')
... 
>>> a=Foo()
>>> b=Bar()
>>> a+b
bar.radd
>>> b+a
bar.add
>>> 

【讨论】:

    【解决方案2】:

    对于表达式lhs + rhs,Python 将首先尝试lhs.__add__(rhs),然后是rhs.__radd__(lhs)

    【讨论】:

      【解决方案3】:

      我也不确定,所以我自己试试

      In [84]: class Foo(object):
          ...:     def __add__(self, rhs):
          ...:         print 'foo.add'
          ...:         
          ...: class Bar(object):
          ...:     def __radd__(self, lhs):
          ...:         print 'bar.radd'
          ...: 
          ...: f=Foo(); b=Bar()
          ...: f+b
          ...: 1+b
      foo.add
      bar.radd
      

      那我现在记住了规则。

      【讨论】:

      • 只有当对象不相关时才如此。如果其中一个对象是另一个对象的子类,则子类总是获胜。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 2011-10-12
      相关资源
      最近更新 更多