public
Last active

Quantity sublcassing tests

  • Download Gist
testqty.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#http://stackoverflow.com/questions/17444657/how-to-prevent-numpy-from-splitting-up-an-array-like-object
 
class Quantity(object):
 
def __init__(self, value, unit):
self.unit = unit
self.value = value
 
def __getitem__(self, key):
return Quantity(self.value[key], unit=self.unit)
 
def __len__(self):
return len(self.value)
 
def __array__(self):
return self.value
 
def __array_wrap__(self, arr, context=None):
return Quantity( np.ndarray.__array_wrap__(self.value, arr, context), self.unit)
 
__array_priority__ = 1000
 
def __repr__(self):
return "<Quantity "+repr(self.value)+" at "+str(id(self))+">"
 
import numpy as np
q = Quantity(np.array([1,2,3],dtype='float'), 'degree')
print "array(q): ",
print(repr(np.array(q)))
 
print "q * [1,3,5]:",
print(repr(q * np.array([1,3,5])))
print "[1,3,5] * q:",
print(repr(np.array([1,3,5]) * q))
print "q: ",
print(repr(q))
 
"""
$ python testqty.py
array(q): array([ 1., 2., 3.])
q * [1,3,5]: <Quantity array([ 1., 6., 15.]) at 4317007184>
[1,3,5] * q: <Quantity array([ 1., 6., 15.]) at 4317007184>
q: <Quantity array([ 1., 2., 3.]) at 4317007056>
"""

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.