Adding Values From Tuples of Same Length

后端 未结 6 994
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 05:07

In a graphical program I\'m writing using pygame I use a tuple representing a coordinate like this: (50, 50).

Sometimes, I call a function which returns another tupl

6条回答
  •  情书的邮戳
    2020-12-06 05:22

    To get your "+" and "+=" behaviour you can define your own class and implement the __add__() method. The following is an incomplete sample:

    # T.py
    class T(object):
        def __init__(self, *args):
            self._t = args
        def __add__(self, other):
            return T(*([sum(x) for x in zip(self._t, other._t)]))
        def __str__(self):
            return str(self._t)
        def __repr__(self):
            return repr(self._t)
    
    >>> from T import T
    >>> a = T(50, 50)
    >>> b = T(3, -5)
    >>> a
    (50, 50)
    >>> b
    (3, -5)
    >>> a+b
    (53, 45)
    >>> a+=b
    >>> a
    (53, 45)
    >>> a = T(50, 50, 50)
    >>> b = T(10, -10, 10)
    >>> a+b
    (60, 40, 60)
    >>> a+b+b
    (70, 30, 70)
    

    EDIT: I've found a better way...

    Define class T as a subclass of tuple and override the __new__ and __add__ methods. This provides the same interface as class tuple (but with different behaviour for __add__), so instances of class T can be passed to anything that expects a tuple.

    class T(tuple):
        def __new__(cls, *args):
            return tuple.__new__(cls, args)
        def __add__(self, other):
            return T(*([sum(x) for x in zip(self, other)]))
        def __sub__(self, other):
            return self.__add__(-i for i in other)
    
    >>> a = T(50, 50)
    >>> b = T(3, -5)
    >>> a
    (50, 50)
    >>> b
    (3, -5)
    >>> a+b
    (53, 45)
    >>> a+=b
    >>> a
    (53, 45)
    >>> a = T(50, 50, 50)
    >>> b = T(10, -10, 10)
    >>> a+b
    (60, 40, 60)
    >>> a+b+b
    (70, 30, 70)
    >>> 
    >>> c = a + b
    >>> c[0]
    60
    >>> c[-1]
    60
    >>> for x in c:
    ...     print x
    ... 
    60
    40
    60
    

提交回复
热议问题