zoo.html
001| """My Python Zoo.
001|
001| A collection of Interesting and Fun Objects.
001|
001| classes:
001| widget (name, stuff)
001| SerialNumber (start=1, incr=1)
001| MessageID ()
001| UniqueIdentifier (length)
001|
001| B (name, tag=None)
001| D (B) (name, a=0, b=0)
001| E (D) (name, tag)
001|
001| T (tuple) (meta, data)
001| MSG (T) (name, target, params)
001|
001| Item (name]
001| SubItem (Item) (name, obj=None)
001| ListItem (Item) (name, lst=[])
001|
001| point2 (x, y)
001| point3 (x, y, z)
001|
001| logger (subj, mesg=None, code=5)
001|
001| demo functions:
001| demo_B_D_E_T_MSG ()
001| demo_Items ()
001|
001| Developer@Sonnack.com
001| May 2010
001| """
002|
003| from datetime import datetime
004| from time import time
005| from math import sqrt, atan2, degrees
006| from random import random
007| from goodies import comp, UID
008|
009|
010|
011|
012|
013|
014| class widget:
015| '''A Widget!'''
016|
017| def __init__ (self, name, stuff):
018| self.uid = '%016x' % UID()
019| self.name = name
020| self.stuff = stuff
021|
022| def __str__ (self):
023| return self.name
024|
025| def __repr__ (self):
026| return '%s (%s)' % (self.name, repr(self.stuff))
027|
028| def __call__ (self):
029| return self.stuff
030|
031|
032|
033|
034| class SerialNumber:
035| '''Serial Number class.'''
036|
037| def __init__(self, start=1, incr=1):
038| self._sn = int(start)
039| self._ix = int(incr)
040|
041| def __str__(self):
042| return str(self._sn)
043|
044| def __call__(self):
045| self._sn += self._ix
046| return self._sn
047|
048|
049|
050|
051| class MessageID:
052| def __init__ (self):
053| self.ts = int(1000*time()) * (1+int((2**22)*random()))
054|
055| def __call__ (self):
056| return hex(self.ts)
057|
058| def __str__ (self):
059| return str(self.ts)
060|
061| def __repr__ (self):
062| return hex(id(self))
063|
064|
065| class UniqueIdentifier:
066| '''\
066| Unique Identifier class.
066|
066| methods:
066| obj() - return new UID
066| len(obj) - return UID data string length
066| str(obj) - return current UID
066| '''
067| syms = '@01Aa2Bb3Cc4De5Ee6Ff7Gg8Hh9IiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz_'
068|
069| def __init__ (self, length=16):
070| self.base = len(self.syms)
071| self.slen = length
072| self._data = [int(random() * self.base) for _ in range(self.slen)]
073|
074| def __call__ (self):
075|
076| self._data[0] += 1
077|
078| carry = 0
079| for ix,d in enumerate(self._data):
080| if carry:
081| d += carry
082| self._data[ix] = d
083| carry = 0
084| if self.base <= d:
085| self._data[ix] = (d - self.base)
086| carry = 1 + (d % self.base)
087| if carry:
088| raise OverflowError
089| return str(self)
090|
091| def __len__ (self):
092| return len(self._data)
093|
094| def __str__ (self):
095| s = [self.syms[d] for d in reversed(self._data)]
096| return ''.join(s)
097|
098|
099|
100|
101| class logger:
102| '''\
102| Log Entry Class.
102|
102| properties:
102| .ts - Log Entry TimeStamp
102| .code - Log Entry Level
102| .subj - Log Entry Subject
102| .mesg - Log Entry Message
102|
102| methods:
102| if obj: - non-zero test (length of Message)
102| len(obj) - length of Message string
102| str(obj) - string
102| repr(obj) - JSON-like string
102| cmp(obj,alt) - compare LogEntry objects
102|
102| '''
103| cache = []
104|
105| def __init__ (self, subj, mesg=None, code=5):
106| self.ts = datetime.now()
107| self.code = int(code)
108| self.subj = str(subj)
109| self.mesg = mesg if mesg else ''
110| logger.cache.append(self)
111|
112| def __len__ (self):
113| return len(self.mesg)
114|
115| def __bool__ (self):
116| return 0 < len(self.mesg)
117|
118| def __str__ (self):
119| ts = self.ts.strftime('%b %d %Y %H:%M')
120| t = (ts, self.code, self.subj)
121| s = '%s (%d) %s'
122| return s % t
123|
124| def __repr__ (self):
125| t = (self.ts, self.code, self.subj)
126| s = '{LogEntry: {ts:"%s", code:"%d", subj:"%s"}}'
127| return s % t
128|
129| @classmethod
130| def clear (cls):
131| logger.cache = []
132|
133|
134|
135|
136| class B:
137| '''Base class.'''
138| __level = 'Base'
139|
140| def __new__ (cls, name, tag=None):
141| return super().__new__(cls)
142|
143| def __init__ (self, name, tag=None):
144| self._name = name
145| self._tag = tag if tag else ''
146| self._props = {}
147|
148| def __getattr__ (self, name):
149| '''Getter for virtual properties.'''
150| if name == 'iid': return id(self)
151| if name == 'name': return self._name
152| if name == 'tag': return self._tag
153| if name == 'classname': return self.__class__.__name__
154| raise AttributeError('Unknown Attribute: "%s"' % name)
155|
156| def __setattr__ (self, name, value):
157| '''Setter for virtual properties.'''
158| if name.startswith('_'):
159| super().__setattr__(name, value)
160| return
161| if name in ['tag']:
162| super().__setattr__(name, value)
163| return
164| if name in ['iid', 'name', 'classname']:
165| raise AttributeError('Read-Only Attribute: "%s"' % name)
166| raise AttributeError('That is not permitted!')
167|
168| def __len__ (self):
169| '''Return length of property list.'''
170| return len(self._props)
171|
172| def __iter__(self):
173| '''Get an iterator.'''
174| return iter(self._props)
175|
176| def __getitem__(self, name):
177| '''Get property value.'''
178| if name not in self._props:
179| raise KeyError('Property not found: "%s"' % name)
180| return self._props[name]
181|
182| def __setitem__(self, name, value):
183| '''Set property value.'''
184| if name not in self._props:
185| raise KeyError('Property not found: "%s"' % name)
186| self._props[name] = value
187|
188| def __delitem__ (self, ix):
189| raise NotImplementedError('Property Delete: Not Supported')
190|
191| def __bool__ (self):
192| return True
193|
194| def __str__ (self):
195| v = (' (%s)' % self.tag) if len(self.tag) else ''
196| s = '%s%s'
197| t = (self.name, v)
198| return s % t
199|
200| def __repr__ (self):
201| s = '{B:{name:"%s", tag:"%s", id:%s}, c:%s, level:%s}'
202| t = (self.name, self.tag, hex(self.iid), self.classname, self.__level)
203| return s % t
204|
205|
206|
207|
208| class D (B):
209| '''Derived class.'''
210| __level = 'Derived'
211|
212| def __new__ (cls, name, a=0, b=0):
213| return super().__new__(cls, name)
214|
215| def __init__ (self, name, a=0, b=0):
216| super().__init__(name)
217| self._va = a
218| self._vb = b
219|
220| def __getattr__ (self, name):
221| '''Getter for virtual properties.'''
222| if name == 'va': return self._va
223| if name == 'vb': return self._vb
224| return super().__getattr__(name)
225|
226| def __setattr__ (self, name, value):
227| '''Setter for virtual properties.'''
228| if name in ['va', 'vb']:
229| super().__setattr__(name, value)
230| return
231| super().__setattr__(name, value)
232|
233| def __str__ (self):
234| v = ('[%s]' % self.tag) if len(self.tag) else ''
235| s = '%s%s: ("%s", "%s")'
236| t = (self.name, v, self.va, self.vb)
237| return s % t
238|
239| def __repr__ (self):
240| r = super().__repr__()
241| s = '{D:{parent:%s, va:"%s", vb:"%s"}, level:%s}'
242| t = (r, self.va, self.vb, self.__level)
243| return s % t
244|
245|
246|
247|
248| class E (D):
249| '''\
249| Extended class.
249|
249| given: obj = E('eggs','spam')
249| then:
249| { E:
249| { parent:
249| { D:
249| { parent:
249| { B:
249| { name:"eggs"
249| , tag:"spam"
249| , id:0x2ec5ef0
249| }
249| , c:E
249| , level:Base
249| }
249| , va:"0"
249| , vb:"0"
249| }
249| , level:Derived
249| }
249| }
249| , level:Extended
249| }
249| '''
250| __level = 'Extended'
251|
252| def __new__ (cls, name, tag):
253| return super().__new__(cls, name)
254|
255| def __init__ (self, name, tag):
256| super().__init__(name)
257| self.tag = tag
258|
259| def __str__ (self):
260| v = ('[%s]' % self.tag) if len(self.tag) else ''
261| s = '%s%s: ("%s", "%s")'
262| t = (self.name, v, self.va, self.vb)
263| return s % t
264|
265| def __repr__ (self):
266| r = super().__repr__()
267| s = '{E:{parent:%s}, level:%s}'
268| t = (r, self.__level)
269| return s % t
270|
271|
272|
273|
274|
275|
276| class T (tuple):
277| '''Extended Tuple class.'''
278|
279| def __new__ (cls, meta, data):
280| obj = super().__new__(cls, [meta]+data)
281| return obj
282|
283| def __init__ (self, meta, data):
284| super().__init__()
285|
286| def __getattr__ (self, name):
287| '''Getter for virtual properties.'''
288| if name == 'objtype': return self[0]
289| raise AttributeError('Unknown Attribute: "%s"' % name)
290|
291| def __setattr__ (self, name, value):
292| '''Setter for virtual properties.'''
293| if name in ['objtype']:
294| raise AttributeError('Read-Only Attribute: "%s"' % name)
295| super().__setattr__(name, value)
296|
297|
298| class MSG (T):
299| def __new__ (cls, name, target, params):
300| obj = super().__new__(cls, 'MSG', [name, target]+params)
301| return obj
302|
303| def __init__ (self, name, target, params):
304| super().__init__('msg', None)
305|
306| def __getattr__ (self, name):
307| '''Getter for virtual properties.'''
308| if name == 'name': return self[1]
309| if name == 'target': return self[2]
310| if name == 'params': return self[3]
311| return super().__getattr__(name)
312|
313| def __setattr__ (self, name, value):
314| '''Setter for virtual properties.'''
315| if name in ['name', 'target', 'params']:
316| raise AttributeError('Read-Only Attribute: "%s"' % name)
317| super().__setattr__(name, value)
318|
319| def __str__ (self):
320| s = 'MSG[%s] %s (%d)'
321| t = (self.name, self.target, self.params[0])
322| return s % t
323|
324|
325| def demo_B_D_E_T_MSG ():
326| bb = B('alice', tag='chris')
327|
328| dd = D('barb', a=3002, b=4.13325)
329| dd.tag = 'james'
330| dd.va = 100
331| dd.vb = -12
332|
333| ee = E('carol', 'fred')
334| ee.va = -12
335| ee.vb = 0.8729999
336|
337| t0 = T('msg', [('text/mesgname','set'), ('addr',34), (1,('addr',21))])
338| t1 = T('point', [42, -1])
339| t2 = T('triple', [1, 2, 3])
340| t3 = T('list', [10, 0,10,20,30,40,50,60,70,80,90])
341|
342| mm = MSG('open', ('addr',1234), [ (2,('addr',5678),('addr',5678)), (1,('addr',5520)), (2,('addr',5382),('addr',5355)) ])
343| return (bb, dd, ee, t0,t1,t2,t3, mm)
344|
345|
346|
347|
348|
349| class Item:
350| '''Basic Named Item Class.'''
351| SN = SerialNumber()
352|
353| def __init__ (self, name):
354| '''Create new Item instance.'''
355| self._iid = self.SN()
356| self._created = datetime.now()
357| self._updated = self._created
358| self._mods = 0
359| self._name = name
360|
361| def update (self):
362| '''Update this instance.'''
363| self._updated = datetime.now()
364| self._mods += 1
365|
366| def __getattr__ (self, name):
367| '''Getter for virtual properties.'''
368| if name == 'iid': return self._iid
369| if name == 'name': return self._name
370| if name == 'created': return self._created.strftime('%m-%d-%Y %H:%M:%S')
371| if name == 'updated': return self._updated.strftime('%m-%d-%Y %H:%M:%S')
372| if name == 'mods': return self._mods
373| raise AttributeError('Unknown Attribute: "%s"' % name)
374|
375| def __setattr__ (self, name, value):
376| '''Setter for virtual properties.'''
377| if name.startswith('_'):
378| super().__setattr__(name, value)
379| return
380| if name in ['iid', 'name', 'created', 'updated', 'mods']:
381| raise AttributeError('Read-Only Attribute: "%s"' % name)
382| raise AttributeError('That is not permitted!')
383|
384| def __cmp__ (self, other):
385| '''Compare two Items. Sort Order: name,iid,created,updated.'''
386| if other == None: return +1
387| if not isinstance(other, Item):
388| raise TypeError("Invalid comparison type: {%s}" % type(other))
389| return comp(self._name, other._name) or comp(self._iid, other._iid) or comp(self._created, other._created) or comp(self._updated, other._updated) or comp(id(self), id(other))
390|
391| def __str__ (self):
392| '''String version.'''
393| s = '%s [%s][%s]'
394| t = (self.name, self.created, self.updated)
395| return s % t
396|
397| def __repr__ (self):
398| '''JSON-like string.'''
399| s = '{Item:{name:"%s", iid:%d, created:"%s", updated:"%s", mods:%d, addr:%s}}'
400| t = (self.name, self.iid, self.created, self.updated, self.mods, hex(id(self)))
401| return s % t
402|
403|
404|
405|
406| class SubItem (Item):
407| '''Basic Sub-Item Class.'''
408| Messages = ['q', 'x', 'w']
409|
410| def __init__ (self, name, obj=None):
411| '''Create new SubItem instance.'''
412| super().__init__(name)
413| self._payload = obj
414|
415| def get (self):
416| '''Get the instance contents.'''
417| return self._payload
418|
419| def put (self, obj):
420| '''Put the instance contents.'''
421| if obj:
422| self._payload = obj
423| self.update()
424|
425| def __bool__ (self):
426| '''Instance is FALSE if no payload.'''
427| return (self._payload != None)
428|
429| def __cmp__ (self, other):
430| '''Compare two SubItems.'''
431| if other == None: return +1
432| if not isinstance(other, SubItem):
433| raise TypeError("Invalid comparison type: {%s}" % type(other))
434|
435| if (not self) and (not other): return 0
436|
437| if not self: return -1
438| if not other: return +1
439|
440| return super().__cmp__(other)
441|
442| def __str__ (self):
443| '''String version.'''
444| r = super().__str__()
445| s = '%s {%s}'
446| t = (r, type(self._payload))
447| return s % t
448|
449| def __repr__ (self):
450| '''JSON-like string.'''
451| r = super().__repr__()
452| s = '{SubItem:{parent:%s, type:"%s"}}'
453| t = (r, type(self._payload))
454| return s % t
455|
456|
457|
458|
459| class ListItem (Item):
460| '''Basic List-Item Class.'''
461|
462| def __init__ (self, name, lst=[]):
463| '''Create new ListItem instance.'''
464| super().__init__(name)
465| self._items = []
466| if lst:
467| self._items.extend(lst)
468|
469| def get (self):
470| '''Get the instance contents.'''
471| return self._items
472|
473| def put (self, lst):
474| '''Set the instance contents.'''
475| if lst:
476| self._items = []
477| self._items.extend(lst)
478| self.update()
479|
480| def add (self, lst):
481| '''Add to the instance contents.'''
482| if lst:
483| self._items.extend(lst)
484| self.update()
485|
486| def __bool__ (self):
487| '''Instance is FALSE if no items in list.'''
488| return (0 < len(self))
489|
490| def __cmp__ (self, other):
491| '''Compare two ListItems.'''
492| if other == None: return +1
493| if not isinstance(other, ListItem):
494| raise TypeError("Invalid comparison type: {%s}" % type(other))
495|
496| if (not self) and (not other): return 0
497|
498| if not self: return -1
499| if not other: return +1
500|
501| return comp(len(self), len(other)) or super().__cmp__(other)
502|
503| def __len__ (self):
504| '''Return length of list.'''
505| return len(self._items)
506|
507| def __getitem__(self, ix):
508| '''Get Nth item in list.'''
509| if not isinstance(ix, int):
510| raise TypeError("Index must be an int!")
511| if (ix < 0) or (len(self) <= ix):
512| raise IndexError('Index out of range: %d' % ix)
513| return self._items[ix]
514|
515| def __iter__(self):
516| '''Get an iterator.'''
517| return iter(self._items)
518|
519| def __str__ (self):
520| '''String version.'''
521| r = super().__str__()
522| s = '%s {%s[%d]}'
523| t = (r, type(self._items[0] if len(self) else None), len(self._items))
524| return s % t
525|
526| def __repr__ (self):
527| '''JSON-like string.'''
528| r = super().__repr__()
529| s = '{ListItem:{parent:%s, length:"%s"}}'
530| t = (r, len(self._items))
531| return s % t
532|
533|
534| def demo_Items ():
535| g1 = Item("Frisker")
536| g2 = Item("Aggi")
537| g3 = SubItem("Lola")
538| g4 = SubItem("Lola", (0,17,'eggs'))
539| g5 = ListItem("Christie", [(34,19,'shop'), ('tag','Dane'), ('tag','Guard'), 3,9,0])
540| g6 = ListItem("Molly")
541| g7 = SubItem("Sam", [('properties',{'name':'Samantha', 'link':'pet', 'type':'dog'}), ('catalog',{'sex':'female', 'breed':'lab', 'color':'black', 'tags':('dog','best','last','6th','past')}),('marker','eof')] )
542| return (g1, g2, g3, g4, g5, g6, g7)
543|
544|
545|
546| class point2:
547| '''Basic XY Point Class.'''
548|
549|
550|
551| def radius (self):
552| '''Radius: x^2 + y^2 = r^2.'''
553| return sqrt((self.x * self.x) + (self.y * self.y))
554|
555| def distance (self, other):
556| ''' Distance from one point to another. '''
557| dx = self.x - other.x
558| dy = self.y - other.y
559| return sqrt((dx*dx) + (dy*dy))
560|
561| def angle (self):
562| '''Angle: arc tangent of y/x.'''
563| return degrees(atan2(self.y, self.x))
564|
565| def coords (self):
566| '''Return XY coordinates (as a tuple). [alias for astuple]'''
567| return self.astuple()
568|
569| def polar (self):
570| '''Return polar coordinates (as a tuple).'''
571| return (self.radius(), self.angle())
572|
573| def astuple (self): return (self.x, self.y)
574| def aslist (self): return [self.x, self.y]
575| def asdict (self): return {'x':self.x, 'y':self.y}
576|
577|
578|
579| def __bool__ (self):
580| return True if (self.x or self.y) else False
581|
582| def __eq__ (self, other):
583| if isinstance(other,point2):
584| return True if ((self.x == other.x) and (self.y == other.y)) else False
585| return False
586|
587| def __ne__ (self, other): return not self.__eq__(other)
588|
589| def __lt__ (self, other): return self.radius() < other.radius()
590| def __gt__ (self, other): return self.radius() > other.radius()
591| def __le__ (self, other): return self.radius() <= other.radius()
592| def __ge__ (self, other): return self.radius() >= other.radius()
593|
594|
595|
596| def __add__ (self, other):
597| '''Point or Scalar Addition.'''
598| if isinstance(other,int) or isinstance(other,float):
599| nf = float(other)
600| return point2(self.x+nf, self.y+nf)
601| if isinstance(other,point2):
602| return point2(self.x+other.x, self.y+other.y)
603| raise TypeError('Unsupported type for point addition: %s' % type(other))
604|
605| def __sub__ (self, other):
606| '''Point or Scalar Subtration.'''
607| if isinstance(other,int) or isinstance(other,float):
608| nf = float(other)
609| return point2(self.x-nf, self.y-nf)
610| if isinstance(other,point2):
611| return point2(self.x-other.x, self.y-other.y)
612| raise TypeError('Unsupported type for point subtraction: %s' % type(other))
613|
614| def __mul__ (self, other):
615| '''Point or Scalar Multiplication.'''
616| if isinstance(other,int) or isinstance(other,float):
617| nf = float(other)
618| return point2(self.x*nf, self.y*nf)
619| if isinstance(other,point2):
620| return point2(self.x*other.x, self.y*other.y)
621| raise TypeError('Unsupported type for point multiplication: %s' % type(other))
622|
623| def __truediv__ (self, other):
624| '''Point or Scalar Division.'''
625| if isinstance(other,int) or isinstance(other,float):
626| nf = float(other)
627| return point2(self.x/nf, self.y/nf)
628| if isinstance(other,point2):
629| return point2(self.x/other.x, self.y/other.y)
630| raise TypeError('Unsupported type for point division: %s' % type(other))
631|
632| def __radd__ (self, other):
633| '''Scalar Addition.'''
634| return self.__add__(other)
635|
636| def __rsub__ (self, other):
637| '''Scalar Subtraction.'''
638| return self.__sub__(other)
639|
640| def __rmul__ (self, other):
641| '''Scalar Multiplication.'''
642| return self.__mul__(other)
643|
644| def __rtruediv__ (self, other):
645| '''Scalar Division.'''
646| return self.__truediv__(other)
647|
648| def __iadd__ (self, other):
649| '''Point or Scalar In-place Addition.'''
650| if isinstance(other,int) or isinstance(other,float):
651| nf = float(other)
652| self.x += nf
653| self.y += nf
654| return self
655| if isinstance(other,point2):
656| self.x += other.x
657| self.y += other.y
658| return self
659| raise TypeError('Unsupported type for point addition: %s' % type(other))
660|
661| def __isub__ (self, other):
662| '''Point or Scalar In-place Subtration.'''
663| if isinstance(other,int) or isinstance(other,float):
664| nf = float(other)
665| self.x -= nf
666| self.y -= nf
667| return self
668| if isinstance(other,point2):
669| self.x -= other.x
670| self.y -= other.y
671| return self
672| raise TypeError('Unsupported type for point subtraction: %s' % type(other))
673|
674| def __imul__ (self, other):
675| '''Point or Scalar In-place Multiplication.'''
676| if isinstance(other,int) or isinstance(other,float):
677| nf = float(other)
678| self.x *= nf
679| self.y *= nf
680| return self
681| if isinstance(other,point2):
682| self.x *= other.x
683| self.y *= other.y
684| return self
685| raise TypeError('Unsupported type for point multiplication: %s' % type(other))
686|
687| def __itruediv__ (self, other):
688| '''Point or Scalar In-place Division.'''
689| if isinstance(other,int) or isinstance(other,float):
690| nf = float(other)
691| self.x /= nf
692| self.y /= nf
693| return self
694| if isinstance(other,point2):
695| self.x /= other.x
696| self.y /= other.y
697| return self
698| raise TypeError('Unsupported type for point division: %s' % type(other))
699|
700| def __pos__ (self):
701| return self
702|
703| def __neg__ (self):
704| return point2(-self.x, -self.y)
705|
706| def __abs__ (self):
707| return point2(abs(self.x), abs(self.y))
708|
709|
710|
711| def __init__ (self, x=0.0, y=0.0):
712| self.x = float(x)
713| self.y = float(y)
714|
715| def __str__ (self):
716| ''' Return pretty string version. '''
717| s = "(%+.3f, %+.3f)"
718| t = (self.x, self.y)
719| return s % t
720|
721| def __repr__ (self):
722| ''' Return Point as a serializable object (JSON). '''
723| s = "{point2:{x:%f, y:%f}}"
724| t = (self.x, self.y)
725| return s % t
726|
727|
728|
729| class point3 (point2):
730| '''Basic XYZ Point Class. (Extends point2.)'''
731|
732|
733|
734| def radius (self):
735| '''Radius: x^2 + y^2 + z^2 = r^2.'''
736| return sqrt((self.x * self.x) + (self.y * self.y) + (self.z * self.z))
737|
738| def distance (self, other):
739| ''' Distance from one point to another. '''
740| dx = self.x - other.x
741| dy = self.y - other.y
742| dz = self.z - other.z
743| return sqrt((dx*dx) + (dy*dy) + (dz*dz))
744|
745| def elevation (self):
746| ''' Elevation: arc tangent of z/xy. '''
747| xy = super().radius()
748| return degrees(atan2(self.z, xy))
749|
750| def coords (self):
751| '''Return XYZ coordinates (as a tuple). [alias for astuple]'''
752| return self.astuple()
753|
754| def polar (self):
755| '''Return polar coordinates (as a tuple).'''
756| return (self.radius(), self.angle(), self.elevation())
757|
758| def astuple (self): return (self.x, self.y, self.z)
759| def aslist (self): return [self.x, self.y, self.z]
760| def asdict (self): return {'x':self.x, 'y':self.y, 'z':self.z}
761|
762|
763|
764| def __bool__ (self):
765| return True if (self.x or self.y or self.z) else False
766|
767| def __eq__ (self, other):
768| if isinstance(other,point3):
769| if (self.x != other.x): return False
770| if (self.y != other.y): return False
771| if (self.z != other.z): return False
772| return True
773| return False
774|
775| def __ne__ (self, other): return not self.__eq__(other)
776|
777| def __lt__ (self, other): return self.radius() < other.radius()
778| def __gt__ (self, other): return self.radius() > other.radius()
779| def __le__ (self, other): return self.radius() <= other.radius()
780| def __ge__ (self, other): return self.radius() >= other.radius()
781|
782|
783|
784| def __add__ (self, other):
785| '''Point or Scalar Addition.'''
786| if isinstance(other,int) or isinstance(other,float):
787| nf = float(other)
788| return point3(self.x+nf, self.y+nf, self.z+nf)
789| if isinstance(other,point3):
790| return point3(self.x+other.x, self.y+other.y, self.z+other.z)
791| raise TypeError('Unsupported type for point addition: %s' % type(other))
792|
793| def __sub__ (self, other):
794| '''Point or Scalar Subtration.'''
795| if isinstance(other,int) or isinstance(other,float):
796| nf = float(other)
797| return point3(self.x-nf, self.y-nf, self.z-nf)
798| if isinstance(other,point3):
799| return point3(self.x-other.x, self.y-other.y, self.z-other.z)
800| raise TypeError('Unsupported type for point subtraction: %s' % type(other))
801|
802| def __mul__ (self, other):
803| '''Point or Scalar Multiplication.'''
804| if isinstance(other,int) or isinstance(other,float):
805| nf = float(other)
806| return point3(self.x*nf, self.y*nf, self.z*nf)
807| if isinstance(other,point3):
808| return point3(self.x*other.x, self.y*other.y, self.z*other.z)
809| raise TypeError('Unsupported type for point multiplication: %s' % type(other))
810|
811| def __truediv__ (self, other):
812| '''Point or Scalar Division.'''
813| if isinstance(other,int) or isinstance(other,float):
814| nf = float(other)
815| return point3(self.x/nf, self.y/nf, self.z/nf)
816| if isinstance(other,point3):
817| return point3(self.x/other.x, self.y/other.y, self.z/other.z)
818| raise TypeError('Unsupported type for point division: %s' % type(other))
819|
820| def __radd__ (self, other):
821| '''Scalar Addition.'''
822| return self.__add__(other)
823|
824| def __rsub__ (self, other):
825| '''Scalar Subtraction.'''
826| return self.__sub__(other)
827|
828| def __rmul__ (self, other):
829| '''Scalar Multiplication.'''
830| return self.__mul__(other)
831|
832| def __rtruediv__ (self, other):
833| '''Scalar Division.'''
834| return self.__truediv__(other)
835|
836| def __iadd__ (self, other):
837| '''Point or Scalar In-place Addition.'''
838| if isinstance(other,int) or isinstance(other,float):
839| nf = float(other)
840| self.x += nf
841| self.y += nf
842| self.z += nf
843| return self
844| if isinstance(other,point3):
845| self.x += other.x
846| self.y += other.y
847| self.z += other.z
848| return self
849| raise TypeError('Unsupported type for point addition: %s' % type(other))
850|
851| def __isub__ (self, other):
852| '''Point or Scalar In-place Subtration.'''
853| if isinstance(other,int) or isinstance(other,float):
854| nf = float(other)
855| self.x -= nf
856| self.y -= nf
857| self.z -= nf
858| return self
859| if isinstance(other,point3):
860| self.x -= other.x
861| self.y -= other.y
862| self.z -= other.z
863| return self
864| raise TypeError('Unsupported type for point subtraction: %s' % type(other))
865|
866| def __imul__ (self, other):
867| '''Point or Scalar In-place Multiplication.'''
868| if isinstance(other,int) or isinstance(other,float):
869| nf = float(other)
870| self.x *= nf
871| self.y *= nf
872| self.z *= nf
873| return self
874| if isinstance(other,point3):
875| self.x *= other.x
876| self.y *= other.y
877| self.z *= other.z
878| return self
879| raise TypeError('Unsupported type for point multiplication: %s' % type(other))
880|
881| def __itruediv__ (self, other):
882| '''Point or Scalar In-place Division.'''
883| if isinstance(other,int) or isinstance(other,float):
884| nf = float(other)
885| self.x /= nf
886| self.y /= nf
887| self.z /= nf
888| return self
889| if isinstance(other,point3):
890| self.x /= other.x
891| self.y /= other.y
892| self.z /= other.z
893| return self
894| raise TypeError('Unsupported type for point division: %s' % type(other))
895|
896| def __pos__ (self):
897| return self
898|
899| def __neg__ (self):
900| return point3(-self.x, -self.y, -self.z)
901|
902| def __abs__ (self):
903| return point3(abs(self.x), abs(self.y), abs(self.z))
904|
905|
906|
907| def __init__ (self, x=0.0, y=0.0, z=0.0):
908| '''Initialize new point3 instance.'''
909| super().__init__(x, y)
910| self.z = float(z)
911|
912| def __str__ (self):
913| ''' Return pretty string version. '''
914| s = "(%+.3f, %+.3f, %+.3f)"
915| t = (self.x, self.y, self.z)
916| return s % t
917|
918| def __repr__ (self):
919| ''' Return Point as a serializable object (JSON). '''
920| s = "{point3:{x:%f, y:%f, z:%f}}"
921| t = (self.x, self.y, self.z)
922| return s % t
923|
924|
925|
926|
927| """eof"""
928|