Last active
December 19, 2015 07:58
-
-
Save keflavich/5921957 to your computer and use it in GitHub Desktop.
Quantity sublcassing tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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> | |
""" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment