Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x Python3方法在加法操作中翻转参数_Python 3.x_Add_Reverse_Datamodel - Fatal编程技术网

Python 3.x Python3方法在加法操作中翻转参数

Python 3.x Python3方法在加法操作中翻转参数,python-3.x,add,reverse,datamodel,Python 3.x,Add,Reverse,Datamodel,我有一个类,它添加了两个点(一个是Point类型,另一个是元组或列表——请参见代码)。我的问题是,我的add方法只有在按特定顺序输入数字时才有效。我需要创建第二个方法(根据本作业中的规则),该方法只包含一行调用add方法并返回结果,并且可以在文档的数据模型中找到 class Point(): def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return ("X = " + st

我有一个类,它添加了两个点(一个是Point类型,另一个是元组或列表——请参见代码)。我的问题是,我的add方法只有在按特定顺序输入数字时才有效。我需要创建第二个方法(根据本作业中的规则),该方法只包含一行调用add方法并返回结果,并且可以在文档的数据模型中找到

class Point():
def __init__(self, x=0, y=0):
    self.x = x
    self.y = y

def __str__(self):
    return ("X = " + str(self.x) + "\nY = " + str(self.y))

def __add__(self, other):
    if isinstance(other,list) or isinstance(other,tuple):
        newX = other[0] + self.x
        newY = other[1] + self.y
        return(Point(newX,newY))
    else:
        newX = self.x + other
        newY = self.y + other
        return(Point(newX,newY))

p = Point(5,10)
print(p + [3.5,6])
print([3.5,6] + p)

我仔细研究了数据模型,我只能认为反向或使用getattr的东西会起作用,但我不知道如何实现这两种方法,或者我是否走上了正确的道路。请帮忙

你应该在你的课堂上添加
\uuuu radd\uuuu()

def __radd__(self, *args, **kwargs):
    return self.__add__(*args, **kwargs)
这实际上会执行一个
\uuuuu add()
,因为在本例中它实际上是相同的

<>但是你可以考虑让这个班级表现得像个列表,这样的事情:

class Point():
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
        self._list = [self.x, self.y]

    def __str__(self):
        return ("X = " + str(self.x) + "\nY = " + str(self.y))

    def __repr__(self):
        return str(self._list)

    def __iter__(self):
        for elem in self._list:
            yield elem

    def __getitem__(self, i):
        return self._list(i)

    def __len__(self):
        return len(self._list)

    def __delitem__(self, i):
        #not sure if you really want this
        del self._list[i]

    def __setitem__(self, i, val):
        #not sure if you really want this
        self._list[i] = val    

    def __add__(self, other):
        #this code could be optimized
        #using your original code for this example
        if isinstance(other,list) or isinstance(other,tuple):
            newX = other[0] + self.x
            newY = other[1] + self.y
        else:
            newX = self.x + other
            newY = self.y + other
        #returning a list
        return [newX, newY]

    def __radd__(self, *args, **kwargs):
        return self.__add__(*args, **kwargs)


p = Point(5,10)
print(p)
print(p + [3.5,6])
print([3.5,6] + p)
输出:

[5, 10]
[8.5, 16]
[8.5, 16]
[8.5, 16]
[8.5, 16]
[10, 14]
[10, 14]
[6.1, 11.1]
[6.1, 11.1]
[5, 10]
[5, 10]
[6, 12]
[6, 12]
[1.5, 4]
[-1.5, -4]
[0, 6]
[0, -6]
[3.9, 8.9]
[-3.9, -8.9]
[5, 10]
[5, 10]
[4, 8]
[-4, -8]
[5, 10]
[编辑]如果您决定使其行为像一个
列表
,您也可以将其子类化为
列表
,例如:

class Point(list):

    def __init__(self, x=0, y=0):
        super(Point, self).__init__([x, y])

    def __add__(self, other):
        if isinstance(other, (list, tuple)):
            return [sum(i) for i in zip(self, other)]
        elif isinstance(other, (int, float)):
            return [i + other for i in self]
        else:
            return self

    def __radd__(self, *args, **kwargs):
        return self.__add__(*args, **kwargs)

    #you probably want a __sub__
    def __sub__(self, other):
        if isinstance(other, (list, tuple)):
            return [i - j for i, j in zip(self, other)]
        elif isinstance(other, (int, float)):
            return [i - other for i in self]
        else:
            return self

    #and an __rsub__
    def __rsub__(self, other):
        if isinstance(other, (list, tuple)):
            return [i - j for i, j in zip(other, self)]
        elif isinstance(other, (int, float)):
            return [other - i for i in self]
        else:
            return self   

    #take away functions you do not want
    def pop(*args, **kwargs): pass
    def sort(*args, **kwargs): pass
    def append(*args, **kwargs): pass
    def extend(*args, **kwargs): pass
    def insert(*args, **kwargs): pass
    def remove(*args, **kwargs): pass
    def reverse(*args, **kwargs): pass

p = Point(5,10)
tests = [[3.5, 6], (5,4), 1.1, 'wrong string', [1, 2, 3]]
for test in tests:
    print(p + test)
    print(test + p)
for test in tests:
    print(p - test)
    print(test - p)   
p.append(4)
print(p)
输出:

[5, 10]
[8.5, 16]
[8.5, 16]
[8.5, 16]
[8.5, 16]
[10, 14]
[10, 14]
[6.1, 11.1]
[6.1, 11.1]
[5, 10]
[5, 10]
[6, 12]
[6, 12]
[1.5, 4]
[-1.5, -4]
[0, 6]
[0, -6]
[3.9, 8.9]
[-3.9, -8.9]
[5, 10]
[5, 10]
[4, 8]
[-4, -8]
[5, 10]

您应该在您的类中添加
\uuuu radd\uuuu()

def __radd__(self, *args, **kwargs):
    return self.__add__(*args, **kwargs)
这实际上会执行一个
\uuuuu add()
,因为在本例中它实际上是相同的

<>但是你可以考虑让这个班级表现得像个列表,这样的事情:

class Point():
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y
        self._list = [self.x, self.y]

    def __str__(self):
        return ("X = " + str(self.x) + "\nY = " + str(self.y))

    def __repr__(self):
        return str(self._list)

    def __iter__(self):
        for elem in self._list:
            yield elem

    def __getitem__(self, i):
        return self._list(i)

    def __len__(self):
        return len(self._list)

    def __delitem__(self, i):
        #not sure if you really want this
        del self._list[i]

    def __setitem__(self, i, val):
        #not sure if you really want this
        self._list[i] = val    

    def __add__(self, other):
        #this code could be optimized
        #using your original code for this example
        if isinstance(other,list) or isinstance(other,tuple):
            newX = other[0] + self.x
            newY = other[1] + self.y
        else:
            newX = self.x + other
            newY = self.y + other
        #returning a list
        return [newX, newY]

    def __radd__(self, *args, **kwargs):
        return self.__add__(*args, **kwargs)


p = Point(5,10)
print(p)
print(p + [3.5,6])
print([3.5,6] + p)
输出:

[5, 10]
[8.5, 16]
[8.5, 16]
[8.5, 16]
[8.5, 16]
[10, 14]
[10, 14]
[6.1, 11.1]
[6.1, 11.1]
[5, 10]
[5, 10]
[6, 12]
[6, 12]
[1.5, 4]
[-1.5, -4]
[0, 6]
[0, -6]
[3.9, 8.9]
[-3.9, -8.9]
[5, 10]
[5, 10]
[4, 8]
[-4, -8]
[5, 10]
[编辑]如果您决定使其行为像一个
列表
,您也可以将其子类化为
列表
,例如:

class Point(list):

    def __init__(self, x=0, y=0):
        super(Point, self).__init__([x, y])

    def __add__(self, other):
        if isinstance(other, (list, tuple)):
            return [sum(i) for i in zip(self, other)]
        elif isinstance(other, (int, float)):
            return [i + other for i in self]
        else:
            return self

    def __radd__(self, *args, **kwargs):
        return self.__add__(*args, **kwargs)

    #you probably want a __sub__
    def __sub__(self, other):
        if isinstance(other, (list, tuple)):
            return [i - j for i, j in zip(self, other)]
        elif isinstance(other, (int, float)):
            return [i - other for i in self]
        else:
            return self

    #and an __rsub__
    def __rsub__(self, other):
        if isinstance(other, (list, tuple)):
            return [i - j for i, j in zip(other, self)]
        elif isinstance(other, (int, float)):
            return [other - i for i in self]
        else:
            return self   

    #take away functions you do not want
    def pop(*args, **kwargs): pass
    def sort(*args, **kwargs): pass
    def append(*args, **kwargs): pass
    def extend(*args, **kwargs): pass
    def insert(*args, **kwargs): pass
    def remove(*args, **kwargs): pass
    def reverse(*args, **kwargs): pass

p = Point(5,10)
tests = [[3.5, 6], (5,4), 1.1, 'wrong string', [1, 2, 3]]
for test in tests:
    print(p + test)
    print(test + p)
for test in tests:
    print(p - test)
    print(test - p)   
p.append(4)
print(p)
输出:

[5, 10]
[8.5, 16]
[8.5, 16]
[8.5, 16]
[8.5, 16]
[10, 14]
[10, 14]
[6.1, 11.1]
[6.1, 11.1]
[5, 10]
[5, 10]
[6, 12]
[6, 12]
[1.5, 4]
[-1.5, -4]
[0, 6]
[0, -6]
[3.9, 8.9]
[-3.9, -8.9]
[5, 10]
[5, 10]
[4, 8]
[-4, -8]
[5, 10]

很明显,我没有很好地阅读文档。谢谢你的帮助@vandy,我用一个子类列表的例子更新了答案,这使得代码更易于管理。我显然没有很好地阅读文档。谢谢你的帮助@vandy,我用一个子类列表的例子更新了答案,这使得代码更易于管理