Python refactoring
Both the add and sub are very similar. How does one re-factor code like this? The logic is basically inverse of each other.
class point(object):
def __init__( self, x, y ):
self.x, self.y = x, y
def add( self, p ):
x = self.x + p.x
y = self.y + p.y
return point( x, y )
def sub( self, p ):
x = self.x - p.x
y = self.y - p.y
return point( x, y )
First, standard practice is to capitalize classes (so
Point, notpoint). I’d make use of the__add__and__sub__(and possibly__iadd__and__isub__) methods, as well. A first cut might look like this:I know you’re looking to pull the logic out into a single method, something like:
… but that seems more complicated, without much gain.