Python:“ __ iadd__”和“ + =”具有不同的效果

时间:2018-08-18 16:35:20

标签: python operator-keyword

我对__ior__函数有问题,所以我检查了一下,而__ipow____iadd__发生了同样的事情(没有检查其他人),所以我遇到了很难找出问题所在。

这里仅是为了举例说明(Python 3.6)而已:

 class Integer :
    def __init__(self, value = 0):
        self.val = value

    def __str__(self):
        return str(self.val)

    def add(self, addVal):
        return (self.val + addVal)

    def __add__(self, addVal):
        return (self.val + addVal)    ### Yep, this is the same as above

    def inPlaceAdd(self, addVal):
        self.val += addVal

    def __iadd__(self, addVal):
        self.val += addVal            ### Again

测试时:

== RESTART: C:/(...).py ==
>>> a = Integer()
>>> print(a)
0
>>> a.add(4)
4                     ### As expected
>>> print(a)
0                     ### We didn't want a to change : so far no problem
>>> a.__add__(4)
4                     ### Calling __add__ isn't very pretty, but it works fine
>>>print(a)
0                     ### Just to make sure...
>>> a + 4
4                     ### So far so good.
>>> print(a)
0                     ### Alright...
>>> a.inPlaceAdd(4)
>>> print(a)
4                     ### Nice, that works.
>>> a.__iadd__(4)
>>> print(a)
8                     ### Okay...
>>> a += 4
>>> print(a)
None                  ### :-(
>>> 

第二个版本:__iadd__的定义已被注释掉,没有其他更改。

class Integer :
    def __init__(self, value = 0):
        self.val = value

    def __str__(self):
        return str(self.val)

    def add(self, addVal):
        return (self.val + addVal)

    def __add__(self, addVal):
        return (self.val + addVal)

    def inPlaceAdd(self, addVal):
        self.val += addVal

##  def __iadd__(self, addVal):
##      self.val += addVal

以下是相同测试的结果:

== RESTART: C:/(...).py ==
>>> a = Integer()
>>> print(a)
0
>>> a.add(4)
4
>>> print(a)
0
>>> a + 4
4
>>> print(a)
0
>>> a.inPlaceAdd(4)
>>> print(a)
4                             ### So far everything is the same
>>> a.__iadd__(4)
Traceback (most recent call last):
  File "<pyshell#139>", line 1, in <module>
    a.__iadd__(4)
AttributeError: 'Integer' object has no attribute '__iadd__'
                             ### Anything else would have been unexpected
>>> a += 4                   ### How is that not an error ?
>>> print(a)
8                            ### And why does it work better than when defined explicitly ?
>>> 

那么为什么+=在且仅当未明确定义__iadd__时不起作用?我不认为语法是错误的,因为我看到多个网站引用了__ior____iadd__等,但是问题又是什么呢?

0 个答案:

没有答案