python_classes_2.html


001| """Python Classes (aka 'data types')."""
002| 
003| typename = lambda obj: type(obj).__name__
004| 
005| class point:
006|     """Implements an X-Y point."""
007| 
008|     def __init__ (self, x:float=0.0, y:float=0.0):
009|         """Initialize point."""
010|         self.x = float(x)
011|         self.y = float(y)
012| 
013|     def __str__ (self):
014|         """Return a printable string version."""
015|         return f'[{self.x:+.3f}, {self.y:+.3f}]'
016| 
017|     def __repr__ (self):
018|         """Return a debug string."""
019|         return f'<{typename(self)} @{id(self):012x}>'
020| 
021|     def __bool__ (self):
022|         """Return True is non-zero, otherwise False."""
023|         return (bool(self.x) or bool(self.y))
024| 
025|     def __eq__ (self, other):
026|         """Test for equality with other point."""
027|         if not isinstance(other, type(self)):
028|             raise ValueError(f"Can't compare a point with a {typename(other)}.")
029|         if self.x != other.x: return False
030|         if self.y != other.y: return False
031|         return True
032| 
033|     def __ne__ (self, other):
034|         """Test for non-equality with other point."""
035|         return not self.__eq__(other)
036| 
037|     @classmethod
038|     def from_complex (cls, z:complex):
039|         """Create point from complex number."""
040|         return cls(z.real, z.imag)
041| 
042|     def __complex__ (self):
043|         """Return complex number (x, yi)."""
044|         return complex(self.x, self.y)
045| 
046|     @classmethod
047|     def from_list (cls, lst):
048|         """Create point from first two items in a list."""
049|         x = float(lst[0])
050|         y = float(lst[1])
051|         return cls(x, y)
052| 
053|     def __len__ (self):
054|         """Return 'length' of point (always 2)."""
055|         return 2
056| 
057|     def __getitem__ (self, ix):
058|         """Return a point element by index (0 or 1)."""
059|         if ix == 0: return self.x
060|         if ix == 1: return self.y
061|         raise IndexError(f"Illegal index for a point. ({ix})")
062| 
063|     def __setitem__ (self, ix, value):
064|         """Set a point element by index (0 or 1)."""
065|         if ix == 0: self.x = float(value); return
066|         if ix == 1: self.y = float(value); return
067|         raise IndexError(f"Illegal index for a point. ({ix})")
068| 
069|     def __iter__ (self):
070|         """Return an iterator over the point elements."""
071|         return iter([self.x, self.y])
072| 
073|     def __add__ (self, other):
074|         """Add two points together; return new point."""
075|         if not isinstance(other, type(self)):
076|             raise ValueError(f"Can't add point and {typename(other)}.")
077|         x = self.x + other.x
078|         y = self.y + other.y
079|         return type(self)(x, y)
080| 
081|     def __radd__ (self, other):
082|         """Add a point with something else."""
083|         raise ValueError(f"Can't add {typename(other)} and point.")
084| 
085|     def __iadd__ (self, other):
086|         """Add a point to self; return self."""
087|         if not isinstance(other, type(self)):
088|             raise ValueError(f"Can't add {typename(other)} to point.")
089|         self.x += other.x
090|         self.y += other.y
091|         return self
092| 
093|     def clear (self):
094|         """Reset point to zero."""
095|         self.x = 0.0
096|         self.y = 0.0
097|         return self
098| 
099|     def move (self, x:float=None, y:float=None):
100|         """Set point to new coordinates."""
101|         if x is not None:
102|             self.x = float(x)
103|         if y is not None:
104|             self.y = float(y)
105|         return self
106| 
107| 
108| 
109| def main ():
110|     """Exercise the point class and return some points."""
111| 
112|     # Create a bunch of new points...
113|     pt0 = point()
114|     pt1 = point(1, 2)
115|     pt2 = point(-3, -1.5)
116|     pt3 = point.from_complex(complex(0,-1))
117|     pt4 = point.from_list([2.1, 4.2])
118|     pt5 = pt2 + pt4
119| 
120|     try: p = pt1 + 8.9
121|     except Exception as e: print(e)
122| 
123|     try: p = 8.9 + pt1
124|     except Exception as e: print(e)
125| 
126|     try: pt2 += 6.5
127|     except Exception as e: print(e)
128|     print()
129| 
130|     # Put points in a tuple...
131|     pts = (pt0, pt1, pt2, pt3, pt4, pt5)
132| 
133|     # Print the points...
134|     for pt in pts:
135|         print(f'{pt} {pt!r} [{"T" if pt else "F"}]')
136|     print()
137| 
138|     return pts
139| 
140| if __name__ == "__main__":
141|     pts = main()
142| """eof"""
143|