__add__两个类对象

Ted*_*boy 5 python class python-2.x

我一直在通过搜索教程来学习Python 2。我发现有关课堂的事情。我在__add__躲闪方法上有些麻烦。我不知道如何添加一个类的2个对象。

要更清楚:

class Add_obj:
    def __init__(self, *num):
        self.num = num

    def __repr__(self):
        return 'Add_obj{}'.format(self.num)

    def __add__(self, other):
        for i in zip(*(self.num + other.num)):
            # and then some codes over here

#when:
obj1 = Add_obj(2, 5)
obj2 = Add_obj(4, 7)
# it should return Add_obj(6, 12)
Run Code Online (Sandbox Code Playgroud)

我知道这不是添加2个对象的最佳方法吗?

MSe*_*ert 4

您可以在 中使用mapwithoperator.add和可迭代解包(使用*__add__。例如:

import operator

class Add_obj:
    def __init__(self, *num):
        self.num = num

    def __repr__(self):
        return 'Add_obj{}'.format(self.num)

    def __add__(self, other):
        return self.__class__(*map(operator.add, self.num, other.num))
Run Code Online (Sandbox Code Playgroud)

它确实返回了“预期的对象”:

>>> obj1 = Add_obj(2, 5)
>>> obj2 = Add_obj(4, 7)
>>> obj1 + obj2
Add_obj(6, 12)
Run Code Online (Sandbox Code Playgroud)

然而,这map并不是真正需要的,它只是实现这一目标的一种非常高效且简短的方法。您还可以使用理解式zip来代替:

def __add__(self, other):
    return self.__class__(*[num1+num2 for num1, num2 in zip(self.num, other.num)])
Run Code Online (Sandbox Code Playgroud)

正如评论中指出的那样,这也可以工作,但当两者具有不同的长度时,可能会给出意想不到的(甚至错误的)结果Add_obj。如果您想禁止添加两个不同大小的对象,您可以引发异常:

def __add__(self, other):
    if len(self.num) != len(other.num):
        raise ValueError('cannot two Add_obj with different lengths')
    ...  # use one of the both approaches from above
Run Code Online (Sandbox Code Playgroud)

例如:

>>> obj1 = Add_obj(2, 5)
>>> obj2 = Add_obj(4, 7, 2)
>>> obj1 + obj2
ValueError: cannot two Add_obj with different lengths
Run Code Online (Sandbox Code Playgroud)

或者你可以用零填充较短的一个:

from itertools import izip_longest as zip_longest  # only zip_longest on Python 3

class Add_obj:

    ...

    def __add__(self, other):
        return self.__class__(*[num1+num2 for num1, num2 in zip_longest(self.num, other.num, fillvalue=0)])
Run Code Online (Sandbox Code Playgroud)

例如:

>>> obj1 = Add_obj(2, 5)
>>> obj2 = Add_obj(4, 7, 2)
>>> obj1 + obj2
Add_obj(6, 12, 2)
Run Code Online (Sandbox Code Playgroud)