Style suggestions/critiques

Michael F. Stemper michael.stemper at gmail.com
Fri Aug 23 15:15:37 EDT 2019


On 20/08/2019 21.57, DL Neil wrote:
> 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

>> 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

> 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?

Played briefly with a dict and decided that it was ugly, too. However,
the following objects seem nice to me:

class Point( ):
  def __init__( self, x, y ):
    self.x = float(x)
    self.y = float(y)

class Line( ):
  def __init__( self, p1, p2 ):
    self.p1 = p1
    self.p2 = p2
  def Slope( self ):
    # Proof of concept only. Won't work on vertical lines
    return (self.p1.y-self.p2.y)/(self.p1.x-self.p2.x)

In use:

^^^ Origin = Point(0,0)
^^^ wayright = Point(7,0)
^^^ xaxis = Line(Origin,wayright)
^^^ identity = Line(Origin,Point(1,1))
^^^ xaxis.Slope()
-0.0
^^^ identity.Slope()
1.0
^^^

(I've changed the 3*'>' prompt to 3*'^' to avoid confusing
news clients.)

This approach eliminates the ad hoc unpacking that I had been doing
and made the accesses to particular items more explicit.

Using this approach involves slightly more typing than my original
approach, which allowed:
^^^ Origin = 0,0
^^^ wayright = 7,0

But, that's not really much more typing, and it'll help me keep in
mind what things are what.

My existing code has a function Intersection(line1,line2) that
calculates where line1 and line2 intersect (assuming that there
is a unique such point). To me, this seems to be the proper
pardigm, since it's clear that line1 and line2 are peers in the
intersection function.

Am I being too fastidious here? Is there any reason that an
idiom such as line1.Intersect( line2 ) would be preferable?


-- 
Michael F. Stemper
Exodus 22:21



More information about the Python-list mailing list