Reputation:
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 )
Upvotes: 1
Views: 1172
Reputation: 54021
What about that:
import operator
class point(object):
def __init__( self, x, y ):
self.x, self.y = x, y
def _do_op(self, op, p):
x = op(self.x, p.x)
y = op(self.y, p.y)
return point(x, y)
def add( self, p ):
return self._do_op(operator.add, p)
def sub( self, p ):
return self._do_op(operator.sub, p)
Upvotes: 2
Reputation: 90191
First, standard practice is to capitalize classes (so Point
, not point
). I'd make use of the __add__
and __sub__
(and possibly __iadd__
and __isub__
) methods, as well. A first cut might look like this:
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, p):
return Point(self.x + p.x, self.y + p.y)
def __sub__(self, p):
return Point(self.x - p.x, self.y - p.y)
I know you're looking to pull the logic out into a single method, something like:
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
def _adjust(self, x, y):
return Point(self.x + x, self.y + y)
def __add__(self, p):
return self._adjust(p.x, p.y)
def __sub__(self, p):
return self._adjust(-p.x, -p.y)
... but that seems more complicated, without much gain.
Upvotes: 2
Reputation: 21079
Here's something you could do.
def __add__(self, p): # used this so that you can add using the + operator
x = self.x + p.x
y = self.y + p.y
return point(x, y)
def __sub__(self, p):
return self + point(-p.x, -p.y)
Upvotes: 0