Style suggestions/critiques

DL Neil PythonList at DancesWithMice.info
Tue Aug 20 22:57:42 EDT 2019


On 21/08/19 9:11 AM, Michael F. Stemper wrote:
> I recently wrote a couple of modules (more to come) to help me
> use the tikz package in TeX/LaTeX. Since it's all to do with
> drawing, I have a lot of points in R^2. Being unimaginative, I
> implemented them as ordered pairs (2-tuples) of floats. E.g.:
> p1 = 3,4
> p2 = 5,6
> 
> Naturally, lines are implemented as ordered pairs[1] of points:
> line = p1,p2
> 
> This all seems reasonably simple and intuitive (to me). However,
> in order to actually do some manipulation, I have stuff like:
> # Unpack the lines
> l1p1,l1p2 = line1
> l1x1,l1y1 = l1p1
> l1x2,l1y2 = l1p2
> l2p1,l2p2 = line2
> l2x1,l2y1 = l2p1
> l2x2,l2y2 = l2p2
> spattered all over. Although this is simple enough, I find it
> aesthetically unappealing.

Agreed, but could more descriptive names be used?


> Is there some better idiom that I should be using, or is this
> really in accord with The Zen of Python?
> [1] (I could have done sets, I suppose, but orientation might be
> useful at some point.)

Assuming that the code does-stuff with/to lines, eg rotate the line 0.2 
radians about some nominated rotational-center; maybe construct a class, eg

class Line():
	def __init__( self, starting_point, ending_point ):
		self.starting_point = starting_point
		self.ending_point = ending_point
	def rotate( self, angle, center ):
		...

The same could also be said for a Point class. However, if they are 
'only' Cartesian coordinates and no methods ever apply(???), then maybe 
named-tuples or a dict?
(thus able to refer to p1.x and p1.y (or p1[ "x" ], etc) )


Using examples from above:

	p1 = Point( 3, 4 )	# p1 = 3,4
	p2 = Point( 5, 6 )	# p2 = 5,6

	line = Line( p1, p2 )	# line = p1,p2

and instead of:
	> l1p1,l1p2 = line1

Do things now appear to be closer to self-documenting?


Also, we can now use:
	p1.x 	#instead of l1p1, and
	p1.y	#instead of l1p2

In fact, chances-are you won't ever do this because any point/line 
manipulation would become a method (hidden-away) within the respective 
class...
-- 
Regards =dn



More information about the Python-list mailing list