Created
August 19, 2017 19:18
-
-
Save gabyx/9392992d11bf8550e44002ac7f1ecaaf to your computer and use it in GitHub Desktop.
Points class with names to access columns
This file contains hidden or 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
class Points(np.matrixlib.defmatrix.matrix): | |
def __new__(cls, *args, names=[], **kwargs): | |
o = np.matrixlib.defmatrix.matrix.__new__(cls, *args, **kwargs) | |
# We need to adjust here __class__ | |
# such that o is of type Points and the __init__ get | |
# automatically called | |
o.__class__ = Points | |
return o | |
def __init__(self, *args, names=[], **kwargs): | |
assert(isinstance(names,list)) # Needs to be a list! | |
# Set the attribute self.<pointName> | |
# to a reference of the corresponding column | |
for i,name in enumerate(names): | |
self.__setattr__(name, self[:,i]) | |
# Set the point indices, for the __setattr__ | |
self.__setattr__("pointIndices", {t:i for i,t in enumerate(names)}) | |
def __setitem__(self, name, val): | |
if isinstance(name,str) and hasattr(self, "pointIndices"): | |
if name in self.pointIndices: | |
self[:,self.pointIndices[name]] = val | |
return | |
super(Points, self).__setitem__(name, val) | |
def __getitem__(self, *args, **kwargs): | |
if isinstance(args[0],str) and hasattr(self, args[0]): | |
return getattr(self,args[0]) | |
return super(Points, self).__getitem__(*args, **kwargs) | |
def __setattr__(self,name,val): | |
""" This setter is needed, to make assignment work | |
(e.g self.<pointName> = np.mat([1,2,3]).T) | |
Without this setter: we would accidentally assign | |
self.<pointName> to a new object. | |
""" | |
if hasattr(self, "pointIndices"): | |
if name in self.pointIndices: | |
self[:,self.pointIndices[name]] = val | |
return | |
super(Points, self).__setattr__(name,val) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment