Skip to content

Instantly share code, notes, and snippets.

@lbillingham
Last active June 10, 2016 18:47
Show Gist options
  • Save lbillingham/996adca68bb496b2662eed5158f26676 to your computer and use it in GitHub Desktop.
Save lbillingham/996adca68bb496b2662eed5158f26676 to your computer and use it in GitHub Desktop.
demo class that will take any ascii uppercase keyword argument and add it as an attribute: could be useful for magnetic elements
# -*- coding: utf-8 -*-
"""
Demo class to hold magnetic elements data.
Any keyword argument indexed by an ascii_uppercase letter
will become an attribute
"""
import doctest
import math
import string
POSSIBLE_ELEMENTS = string.ascii_uppercase
def HfromXY(X, Y):
H = math.sqrt(X*X + Y*Y)
return H
def HfromFI(F, I):
H = abs(F * math.cos(I))
return H
class MagElements(object):
""" holds magnetic element data, see __init__ docstring"""
def __init__(self, **kwargs):
"""
Store of magnetic elements data. H
Attributes
----------
all uppercase ASCII letters:
most contain `None` but those initialized will
have real values
Examples
--------
# construct from real keywords
>>> data = MagElements(D=[1,2,3,4], I=[-0.8, -0.6, -0.4, -0.2], \
F=[1, 10, 100, 1000])
>>> data.F
[1, 10, 100, 1000]
>>> len(data.D)
4
>>> data.X is None
True
# construct from a dictionary
>>> my_elems = { \
'X': [3, 5, 40, 24], \
'Y': [4, 12, 9, 7], \
'Z':[1e0, 1e-1, 1e-2, 1e-3] \
}
>>> xyz_data = MagElements(**my_elems)
>>> xyz_data.D is None
True
>>> xyz_data.Y == my_elems['Y']
True
>>> xyz_data.H == [5.0, 13.0, 41.0, 25.0]
True
"""
self._H = None
for element in POSSIBLE_ELEMENTS:
setattr(self, element, kwargs.get(element))
def getH(self):
if self._H is None:
if self._can_computeH_from_XY():
self._H = [HfromXY(x, y) for x, y in zip(self.X, self.Y)]
if self._can_computeH_from_FI():
self._H = [HfromFI(f, i) for f, i in zip(self.F, self.I)]
return self._H
def setH(self, value):
self._H = value
H = property(fget=getH, fset=setH)
def _can_computeH_from_XY(self):
return self.X is not None and self.Y is not None
def _can_computeH_from_FI(self):
return self.F is not None and self.I is not None
if __name__ == '__main__':
# test the examples in the docstrings if we are called as a main module
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment