Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Demo/classes/Vec.py

    r2 r391  
    1 # A simple vector class
     1class Vec:
     2    """ A simple vector class
    23
     4    Instances of the Vec class  can be constructed from numbers
    35
    4 def vec(*v):
    5     return Vec(*v)
     6    >>> a = Vec(1, 2, 3)
     7    >>> b = Vec(3, 2, 1)
    68
     9    added
     10    >>> a + b
     11    Vec(4, 4, 4)
    712
    8 class Vec:
     13    subtracted
     14    >>> a - b
     15    Vec(-2, 0, 2)
    916
     17    and multiplied by a scalar on the left
     18    >>> 3.0 * a
     19    Vec(3.0, 6.0, 9.0)
     20
     21    or on the right
     22    >>> a * 3.0
     23    Vec(3.0, 6.0, 9.0)
     24    """
    1025    def __init__(self, *v):
    1126        self.v = list(v)
    1227
    13     def fromlist(self, v):
     28    @classmethod
     29    def fromlist(cls, v):
    1430        if not isinstance(v, list):
    1531            raise TypeError
    16         self.v = v[:]
    17         return self
     32        inst = cls()
     33        inst.v = v
     34        return inst
    1835
    1936    def __repr__(self):
    20         return 'vec(' + repr(self.v)[1:-1] + ')'
     37        args = ', '.join(repr(x) for x in self.v)
     38        return 'Vec({0})'.format(args)
    2139
    2240    def __len__(self):
     
    2846    def __add__(self, other):
    2947        # Element-wise addition
    30         v = map(lambda x, y: x+y, self, other)
    31         return Vec().fromlist(v)
     48        v = [x + y for x, y in zip(self.v, other.v)]
     49        return Vec.fromlist(v)
    3250
    3351    def __sub__(self, other):
    3452        # Element-wise subtraction
    35         v = map(lambda x, y: x-y, self, other)
    36         return Vec().fromlist(v)
     53        v = [x - y for x, y in zip(self.v, other.v)]
     54        return Vec.fromlist(v)
    3755
    3856    def __mul__(self, scalar):
    3957        # Multiply by scalar
    40         v = map(lambda x: x*scalar, self.v)
    41         return Vec().fromlist(v)
     58        v = [x * scalar for x in self.v]
     59        return Vec.fromlist(v)
    4260
     61    __rmul__ = __mul__
    4362
    4463
    4564def test():
    46     a = vec(1, 2, 3)
    47     b = vec(3, 2, 1)
    48     print a
    49     print b
    50     print a+b
    51     print a-b
    52     print a*3.0
     65    import doctest
     66    doctest.testmod()
    5367
    5468test()
Note: See TracChangeset for help on using the changeset viewer.