Python find method in class -
i have defined class called point defines point in x, y coordinate system. definition , methods shown below. created own version of str method return created point in printable form (required). however, when try pass returned point method determine distance between 2 points (p1 , p2), using call p.distanceto(p2), following error attempt parse string (p2) passed method:
attributeerror: point instance has no attribute 'find'
when pass in string defined p2 should works fine. appreciated. thank you.
here code:
class point: """ define point """ def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "(" + str(self.x) + "," + str(self.y) + ")" def __getitem__(self,i): return def __find__(self,j): return j def distanceto(self,p2): idx1 = p2.find("(") idx2 = p2.find(",") idx3 = p2.find(")") x2 = int(p2[idx1+1:idx2]) y2 = int(p2[idx2+1:idx3]) dist = math.sqrt(math.pow((x2-self.x),2)+math.pow((y2-self.y),2)) return dist p1=point() p2=point(3,4) print p1.distanceto(p2)
you named method __find__
. remove double underscores:
def find(self, j): return j
you should use __...__
"dunder" (double underscore) method names special method names avoid confusion , future name clashes.
however, passing in point
instance, access attributes directly:
def distanceto(self,p2): x2 = p2.x y2 = p2.y dist = math.sqrt(math.pow((x2-self.x),2)+math.pow((y2-self.y),2)) return dist
or, further simplified, using underscore_name style used in python methods:
def distance_to(self, p2): return math.sqrt(math.pow((p2.x - self.x), 2) + math.pow((p2.y - self.y), 2))
you can remove __find__
, __getitem__
methods, attempts @ making .distanceto()
method work.
the full class becomes:
class point(object): """define point""" def __init__(self, x=0, y=0): self.x = x self.y = y def __str__(self): return "({0.x}, {0.y})".format(self) def distance_to(self, p2): return math.sqrt(math.pow((p2.x - self.x), 2) + math.pow((p2.y - self.y), 2))
using little more python idiom class (inheriting object
) , __str__
method (using string formatting).
now class behaves expected:
>>> p1 = point() >>> p2 = point(3,4) >>> print p1 (0, 0) >>> print p2 (3, 4) >>> print p1.distance_to(p2) 5.0
class instances not strings, , although can converted strings (when printed example), don't need treat them strings. access attributes directly.
Comments
Post a Comment