2024-10-28_simple-python-tricks-10.html
001|
002|
003|
004|
005| class my_class_1:
006| ...
007|
008| class my_class_2 (object):
009| ...
010|
011|
012| class a_class:
013| '''A basic user-defined class template.'''
014|
015| def __new__ (cls):
016| '''Create a new instance object.'''
017| return super().__new__(cls)
018|
019| def __init__ (self):
020| '''Initialize new instance object.'''
021| super().__init__()
022|
023| def __str__ (self):
024| '''Return a string version of the object.'''
025| return "An object."
026|
027| obj = a_class()
028| print()
029| print(f'{obj}')
030| print(f'{repr(obj)}')
031| print(f'{type(obj).__name__}')
032| print(f'id={hex(id(obj))}')
033| print()
034|
035| obj.x = 42
036| obj.y = 21
037| print(f'x={obj.x}, y={obj.y}')
038| print()
039|
040|
041| class my_class:
042| '''A basic user-defined class.'''
043|
044| def __new__ (cls, **kwargs):
045| '''Create a new instance object.'''
046| print(f'new({kwargs})')
047|
048|
049| self = super().__new__(cls)
050|
051|
052|
053| print(f'new: {self!r}')
054| return self
055|
056| def __init__ (self, x=0.0, y=0.0):
057| '''Initialize new instance object.'''
058| print(f'init({x} {y})')
059|
060|
061| super().__init__()
062|
063| self.x = x
064| self.y = y
065|
066|
067| print(f'init: {type(self).__name__}:{self}')
068| print()
069|
070| def __repr__ (self):
071| '''Representative string.'''
072| return f'<{self.__class__.__name__} @{hex(id(self))}>'
073|
074| def __str__ (self):
075| '''Pretty-print string.'''
076| return f'[{self.x:.3f}, {self.y:.3f}]'
077|
078|
079| o1 = my_class()
080| o2 = my_class(x=2.7, y=3.1)
081|
082| print(f'object1: {o1} @{hex(id(o1))}')
083| print(f'object2: {o2} @{hex(id(o2))}')
084| print()
085|
086|
087| from math import e,pi
088|
089| class xy_point:
090| '''A simple XY point class.'''
091|
092| def __init__ (self, x=0.0, y=0.0):
093| '''Initialize new point object.'''
094| self.x = x
095| self.y = y
096|
097| def __str__ (self):
098| '''Pretty-print string.'''
099| return f'[{self.x:.6f}, {self.y:.6f}]'
100|
101| p1 = xy_point()
102| p2 = xy_point(x=e, y=pi)
103|
104| print(f'p1: {p1}')
105| print(f'p2: {p2}')
106|
107|
108| class my_list (list):
109| def __new__ (cls, listobject=[]):
110| '''Create a new my_list object.'''
111| print(f'new({listobject})')
112|
113|
114| obj = super().__new__(cls, listobject)
115| print(f'new: {obj}:{type(obj).__name__}')
116|
117|
118|
119| return obj
120|
121| def __init__ (self, listobject=[]):
122| '''Initialize new my_list object.'''
123| print(f'init({listobject})')
124|
125|
126| super().__init__(listobject)
127|
128|
129| print(f'init: {self}:{type(self).__name__}')
130| print()
131|
132|
133|
134| l0 = my_list()
135| l1 = my_list([1,2,3,4,5])
136| l2 = my_list('Hello!')
137| l3 = my_list(range(12))
138| print()
139|
140| print(l0)
141| print(l1)
142| print(l2)
143| print(l3)
144| print()
145|
146|
147| class my_tuple (tuple):
148| def __new__ (cls, *args, **kwargs):
149| '''Create a new my_tuple object.'''
150| print(f'tuple::new({args}, {kwargs})')
151|
152|
153| obj = super().__new__(cls, *args, **kwargs)
154|
155| print(f'tuple::new: {obj}:{type(obj).__name__}')
156|
157|
158| return obj
159|
160| def __init__ (self, *args, **kwargs):
161| '''Initialize new my_tuple object.'''
162| print(f'tuple::init({args}, {kwargs})')
163|
164|
165| super().__init__()
166| print(f'tuple::init: {self}:{type(self).__name__}')
167|
168|
169|
170| class my_dict (dict):
171| def __new__ (cls, *args, **kwargs):
172| '''Create a new my_dict object.'''
173| print(f'dict::new({args}, {kwargs})')
174|
175| obj = super().__new__(cls, *args, **kwargs)
176| print(f'dict::new: {obj}:{type(obj).__name__}')
177|
178|
179|
180| return obj
181|
182| def __init__ (self, *args, **kwargs):
183| '''Initialize new my_dict object.'''
184| print(f'dict::init({args}, {kwargs})')
185|
186|
187| super().__init__(*args, **kwargs)
188|
189| print(f'dict::init: {self}:{type(self).__name__}')
190|
191|
192|
193| class numbers (list):
194| '''Basic list of numbers.'''
195|
196| def __init__ (self, *args):
197| '''Initialize. Takes a single iterable or a list of arguments.'''
198|
199| arglst = list(args[0]) if len(args) == 1 else args
200|
201|
202| for ix,a in enumerate(arglst, start=1):
203| if isinstance(a,int): continue
204| if isinstance(a,float): continue
205| if isinstance(a,complex): continue
206| if isinstance(a,bytes): continue
207| raise ValueError(f'Illegal list item: #{ix}={a}')
208|
209|
210| super().__init__(arglst)
211|
212| def __str__ (self):
213| '''Our string version.'''
214| sn = ','.join([str(n) for n in self])
215| return f'[{sn}]'
216|
217| @property
218| def total (self):
219| '''Return the total.'''
220| return sum(self)
221|
222| @property
223| def mean (self):
224| '''Return the mean (average).'''
225| return sum(self)/len(self)
226|
227| @property
228| def low (self):
229| '''Return the smallest number.'''
230| return min(self)
231|
232| @property
233| def high (self):
234| '''Return the largest number.'''
235| return max(self)
236|
237| @property
238| def sumsquares (self):
239| '''Return the sum of the number squares.'''
240| return sum(self.squares)
241|
242| @property
243| def squares (self):
244| '''Return the squares of the numbers.'''
245| return numbers(pow(a,2) for a in self)
246|
247| @property
248| def cubes (self):
249| '''Return the cubes of the numbers.'''
250| return numbers(pow(a,3) for a in self)
251|
252| from random import randint
253|
254| ns = numbers(randint(10,1000) for _ in range(8))
255| print(ns)
256| print(f'sum = {ns.total}')
257| print(f'avg = {ns.mean:.3f} (min: {ns.low}, max: {ns.high})')
258| print(f'squares: {ns.squares}')
259| print()
260|
261|
262| class point (tuple):
263| '''Base point class.'''
264|
265| def __new__ (cls, *args, **kwargs):
266| '''Create a new point object.'''
267| arglst = list(args[0]) if len(args)==1 else args
268| return super().__new__(cls, arglst)
269|
270| def __init__ (self, *args, precision=3, sep=', '):
271| '''Initialize point object.'''
272| super().__init__()
273| self.precision = precision
274| self.sep = sep
275|
276| def __str__ (self):
277| '''Pretty print string.'''
278| xs = [f'{self[ix]:+.{self.precision}f}' for ix in range(len(self))]
279| return self.sep.join(xs)
280|
281| def dot_product (self, other):
282| '''Return the dot product between this and another point.'''
283| assert isinstance(other,point), ValueError('Invalid object')
284| assert len(self)==len(other), ValueError('Lengths must match.')
285| xs = [a*b for a,b in zip(self,other)]
286| return sum(xs)
287|
288| p1 = point(range(31,42), precision=0, sep=' ')
289| p2 = point(+2.1, -4.2, +6.3, -8.4, precision=2)
290| p3 = point(2.71814, 3.14159, 0.41468, 1.91027, precision=6)
291|
292| print(p1)
293| print(p2)
294| print(p3)
295| print()
296| print(f'p2 dot p2: {p2.dot_product(p2)}')
297| print(f'p2 dot p3: {p2.dot_product(p3)}')
298| print()
299|
300|
301| from json import load as jsonload
302|
303| class config (dict):
304| '''Basic configuration class.'''
305| filename = r"C:\demo\hcc\python\configs.json"
306|
307| def __init__ (self, config_name='<default>'):
308| '''New config instance.'''
309| super().__init__()
310| self['name'] = config_name
311|
312|
313| with open(self.filename, mode='rb') as fp:
314|
315| self.data = jsonload(fp)
316| print('read: %s' % self.filename)
317|
318|
319| self.configs = self.data['configs']
320|
321|
322| self.config = self.configs[config_name]
323|
324|
325| self['lmargin'] = self.config['margin']['left']
326| self['rmargin'] = self.config['margin']['right']
327| self['tmargin'] = self.config['margin']['top']
328| self['bmargin'] = self.config['margin']['bottom']
329| self['lheight'] = self.config['line-height']
330| self['pagnums'] = self.config['page-numbers']
331| self['mode'] = self.config['mode']
332|
333| def __str__ (self):
334| '''Pretty print.'''
335| return f'config[{self["name"]}]'
336|
337| def margin (self):
338| '''Return margin parameters as a tuple.'''
339| lmar = self['lmargin']
340| rmar = self['rmargin']
341| tmar = self['tmargin']
342| bmar = self['bmargin']
343| return (lmar, rmar, tmar, bmar)
344|
345| cfg1 = config()
346| cfg2 = config('8x11')
347| print()
348|
349| print(cfg1)
350| print(f'mode: {cfg1["mode"]}')
351| print('left=%.2f, right=%.2f, top=%.2f, bot=%.2f' % cfg1.margin())
352| print()
353| print(cfg2)
354| print(f'mode: {cfg2["mode"]}')
355| print('left=%.2f, right=%.2f, top=%.2f, bot=%.2f' % cfg2.margin())
356| print()
357|
358|
359| def print_object_info (o):
360| '''List key object attributes.'''
361| print(hex(id(o)))
362| for name in dir(o):
363| print('%-20s: %s' % (name, eval(f'o.{name}')))
364| print()
365|
366|
367| from examples import my_class
368|
369| obj = my_class()
370| print()
371|
372| print(hex(id(obj)))
373| for name in dir(obj):
374| print(name)
375| print()
376|
377|
378| obj_cls = obj.__class__
379| print(hex(id(obj_cls)))
380| print(obj_cls.__name__)
381| for name in dir(obj_cls):
382| print(name)
383| print()
384|
385| obj_typ = obj.__class__.__class__
386| print(hex(id(obj_typ)))
387| print(obj_typ.__name__)
388| for name in dir(obj_typ):
389| print(name)
390| print()
391|
392| print(obj_typ.__class__.mro)
393| print(type.mro(obj_cls))
394| print()
395|
396|
397|