2023-10-17_python-descriptors-part-1.html


001| #:name::Python Descriptors, part 1
002| #:link::https://thehardcorecoder.com/2023/10/17/python-descriptors-part-1/
003| #:date::2023-10-17
004| #:code::
005| class MyClass:
006|     x = MyObject()
007|     y = MyObject()
008| 
009| #:code::
010| class MyClass:
011| 
012|     def __init__ (self):
013|         self.x = MyObject()
014|         self.y = MyObject()
015| 
016| #:code::
017| print(myClass.x, myClass.y)
018| 
019| my_instance = myClass()
020| print(my_instance.x, my_instance.y)
021| 
022| #:code::
023| class myObject:
024|     '''Descriptor class.'''
025|     def __get__ (self, obj, cls):
026|         return '(object)' if obj else '(class)'
027| 
028|     def __set__ (self, obj, val):
029|         print(type(obj).__name__, val)
030| 
031| class myClass:
032|     data = myObject()
033| 
034| 
035| print(myClass.data)
036| 
037| my_instance = myClass()
038| print(my_instance.data)
039| 
040| my_instance.data = 42
041| print(my_instance.data)
042| 
043| #:code::
044| class myObject:
045|     '''Descriptor class.'''
046|     def __get__ (self, obj, cls):
047|         return '(object)' if obj else '(class)'
048| 
049|     def __set__ (self, obj, val):
050|         print(type(obj).__name__, val)
051| 
052| class myClass:
053|     data = myObject()
054| 
055| my_instance = myClass()
056| 
057| print(myClass.data)
058| print(my_instance.data)
059| 
060| myClass.data = 42
061| 
062| print(myClass.data)
063| print(my_instance.data)
064| 
065| #:code::
066| class PointBaseClass:
067|     '''Very simple XY-point base class.'''
068| 
069|     def __init__ (self, x=0.0, y=0.0):
070|         self._x = x
071|         self._y = y
072| 
073|     def __str__ (self):
074|         return '(%f, %f)' % (self._x, self._y)
075| 
076|     def __repr__ (self):
077|         return '<%s @%012x>' % (typename(self), id(self))
078| 
079| 
080| def demo_PointBaseClass ():
081|     # Create new point instance...
082|     pt = PointBaseClass(21, 42)
083|     print(str(pt), repr(pt))
084|     print('x=%s, y=%s\n' % (pt._x, pt._y))
085| 
086|     # Change the X and Y values...
087|     pt._x = 86
088|     pt._y = 99
089|     print('point=%s\n' % str(pt))
090| 
091|     # Delete the X and Y attributes...
092|     del pt._x
093|     del pt._y
094|     print(('_x=%s' % pt._x) if hasattr(pt,'_x') else 'No _x!')
095|     print(('_y=%s' % pt._y) if hasattr(pt,'_y') else 'No _y!')
096| 
097| #:code::
098| class PointSubClass1 (PointBaseClass):
099|     '''Read-only Point class using the @property decorator.'''
100| 
101|     @property
102|     def x (self):
103|         '''Getter function for X.'''
104|         return self._x
105| 
106|     @property
107|     def y (self):
108|         '''Getter function for Y.'''
109|         return self._y
110| 
111| 
112| def demo_PointSubClass1 ():
113|     # Create new point instance...
114|     pt = PointSubClass1(21, 42)
115|     print(str(pt), repr(pt))
116|     print('x=%s, y=%s\n' % (pt.x, pt.y))
117| 
118|     # Change the X and Y values...
119|     try: pt.x = 86
120|     except Exception as e:
121|         print('ERR: %s' % e)
122| 
123|     try: pt.y = 99
124|     except Exception as e:
125|         print('ERR: %s' % e)
126| 
127|     print('point=%s\n' % str(pt))
128| 
129|     # Delete the X and Y attributes...
130|     try: del pt.x
131|     except Exception as e:
132|         print('ERR: %s' % e)
133| 
134|     try: del pt.y
135|     except Exception as e:
136|         print('ERR: %s' % e)
137| 
138|     print(('point.x=%s' % pt.x) if hasattr(pt, 'x') else 'No x Property!')
139|     print(('point.y=%s' % pt.y) if hasattr(pt, 'y') else 'No y Property!')
140| 
141| #:code::
142| class BasicPointClass:
143|     '''Read-only Point class using the @property decorator.'''
144| 
145|     @property
146|     def x (self):
147|         '''Getter function for X.'''
148|         return self._x
149| 
150|     @property
151|     def y (self):
152|         '''Getter function for Y.'''
153|         return self._y
154| 
155|     def __init__ (self, x=0.0, y=0.0):
156|         '''New point instance.'''
157|         self._x = x
158|         self._y = y
159| 
160|     def __str__ (self):
161|         return '(%f, %f)' % (self.x, self.y)
162| 
163| pt = BasicPointClass(42,21)
164| print(pt)
165| print(pt.x, pt.y)
166| 
167| #:code::
168| class numberlist (list):
169|     '''Python list with a .total attribute.'''
170| 
171|     @property
172|     def total (self):
173|         return sum(self)
174| 
175| lst = numberlist(range(12))
176| print(lst)
177| print(lst.total)
178| 
179| #:code::
180| class PointSubClass2 (PointBaseClass):
181|     '''Using the property() function with arbitrary Get/Set/Del methods.'''
182| 
183|     def __init__ (self, x=0.0, y=0.0, x_max=100, y_max=100):
184|         super().__init__(x=x, y=y)
185|         self.x_max = x_max
186|         self.y_max = y_max
187| 
188|     # Getters...
189|     def _getx (self):
190|         '''Get function for X.'''
191|         return self._x
192| 
193|     def _gety (self):
194|         '''Get function for Y.'''
195|         return self._y
196| 
197|     # Setters...
198|     def _setx (self, value):
199|         '''Set function for X.'''
200|         if not (0.0 <= value <= self.x_max):
201|             raise ValueError('Value must be from 0 to %s' % self.x_max)
202|         self._x = value
203| 
204|     def _sety (self, value):
205|         '''Set function for Y.'''
206|         if not (0.0 <= value <= self.y_max):
207|             raise ValueError('Value must be from 0 to %s' % self.y_max)
208|         self._y = value
209| 
210|     # Deleters...
211|     def _delx (self):
212|         '''Delete function for X.'''
213|         self._x = 0.0
214| 
215|     def _dely (self):
216|         '''Delete function for Y.'''
217|         self._y = 0.0
218| 
219|     # Actual X and Y properties...
220|     x = property(_getx, _setx, _delx, 'X property')
221|     y = property(_gety, _sety, _dely, 'Y property')
222| 
223| 
224| def demo_PointSubClass2():
225|     # Create new point instance...
226|     pt = PointSubClass2(21, 42)
227|     print(str(pt), repr(pt))
228|     print('x=%s, y=%s\n' % (pt.x, pt.y))
229| 
230|     # Change the X and Y values...
231|     pt.x = 86
232|     pt.y = 99
233|     print('point=%s\n' % str(pt))
234| 
235|     # Delete the X and Y attributes...
236|     del pt.x
237|     del pt.y
238| 
239|     print(('x=%s' % pt.x) if hasattr(pt, 'x') else 'No x property!')
240|     print(('y=%s' % pt.y) if hasattr(pt, 'y') else 'No y property!')
241| 
242| demo_PointSubClass2()
243| 
244| #:code::
245| class PointSubClass3 (PointBaseClass):
246|     '''Using the @property decorator with Get/Set/Del methods.'''
247| 
248|     def __init__ (self, x=0.0, y=0.0, x_max=100.0, y_max=100.0):
249|         super().__init__(x=x, y=y)
250|         self.x_max = x_max
251|         self.y_max = y_max
252| 
253|     # Getters...
254|     @property
255|     def x (self):
256|         '''Get function for X.'''
257|         return self._x
258| 
259|     @property
260|     def y (self):
261|         '''Get function for Y.'''
262|         return self._y
263| 
264|     # Setters...
265|     @x.setter
266|     def x (self, value):
267|         '''Set function for X.'''
268|         if not (0.0 <= value <= self.x_max):
269|             raise ValueError('Value must be from 0 to %s' % self.x_max)
270|         self._x = value
271| 
272|     @y.setter
273|     def y (self, value):
274|         '''Set function for Y.'''
275|         if not (0.0 <= value <= self.y_max):
276|             raise ValueError('Value must be from 0 to %s' % self.y_max)
277|         self._y = value
278| 
279|     # Deleters...
280|     @x.deleter
281|     def x (self):
282|         '''Delete function for X.'''
283|         self._x = 0.0
284| 
285|     @y.deleter
286|     def y (self):
287|         '''Delete function for Y.'''
288|         self._y = 0.0
289| 
290| 
291| def demo_PointSubClass3():
292|     # Create new point instance...
293|     pt = PointSubClass3(21, 42)
294|     print(str(pt), repr(pt))
295|     print('x=%s, y=%s\n' % (pt.x, pt.y))
296| 
297|     # Change the X and Y values...
298|     pt.x = 86
299|     pt.y = 99
300|     print('point=%s\n' % str(pt))
301| 
302|     # Delete the X and Y attributes...
303|     del pt.x
304|     del pt.y
305| 
306|     print(('x=%s' % pt.x) if hasattr(pt, 'x') else 'No x Property!')
307|     print(('y=%s' % pt.y) if hasattr(pt, 'y') else 'No y Property!')
308| 
309| demo_PointSubClass3()
310| 
311| #:end:code::
312|