We can cache the actual value that the user provided! When a distance is instantiated using km, km ) print () d = Distance ( km = 217 ) print ( 'au:', d. au * AU_KM d = Distance ( au = 1.524 ) print ( 'au:', d. au = km / AU_KM def km ( self ): return self. So I had to look it up (I got it from Pyramid’s source code):Ĭlass Distance : def _init_ ( self, au = None, km = None ): if au is not None : self. Which both makes the logic simpler and saves valuable time. Otherwise Python skips the whole method call, That only gets called if there isn’t yet a. It can be a whole NumPy array of a million elements.īy using one of those unwieldy if self._km is None:Ĭaching checks inside of each unit’s property,īut then I remembered that Python descriptors km needs to be computed over and over againĪ Skyfield distance isn’t always a simple float, With a big if…elif inside that decides what it should do,Īnother problem with the example code above Modern design pattern that I discuss on my Python Patterns site: _new_ ( cls ) # avoid calling _init_() self. It seems cleaner to me to have but a single objectįor each particular distance that Skyfield needs to represent,Īnd to have that object different offer unitsīy making users name the unit they’re asking the Distance def from_au ( cls, au ): self = cls. To represent a distance measured as au (astronomical units)īut I prefer not to have several objects represent one single thing. Uses objects to represent measures like distance and velocity. The background is that my astronomy library Skyfield It becomes a constructor and returns a new instance of the class. Taking a Python data descriptor and enhancing it so that, So here’s an API innovation that I just made a rough implementation of: Home A Descriptor-Constructor in Python.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |