Making a Point Class in Python

前端 未结 4 1995
旧时难觅i
旧时难觅i 2020-12-17 05:28

I am trying to create a class in python titled \"Point.\" I am trying to create a point on a coordinate plane x and y and track them. As well as find the distance between th

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-17 06:17

    • You declared distance as taking an argument p; inside the method you're referring to it as other. Change p to other in the declaration so they match.

    • sqrt() isn't a builtin; you need to do import math and refer to it as math.sqrt().

    • You aren't doing anything with the testPoint() function you declare; you can invoke it by adding a line at the end like:

    print "distance = %s"%(testPoint())

    At that point, your code works and computes a distance of 4.0 between your points.

    Now, some style issues:

    • In Python, you don't generally privatize member variables, and you don't bother writing trivial getters and setters, so you can remove the getX() and getY() methods and just refer to p.X and p.Y directly given a Point p.

    • The math module has a convenient hypotenuse function, so in distance() you can change the return line to return math.hypot(dx,dy).

    • By default, a user defined object has an unattractive string representation:

      <__main__.Point object at 0x1004e4550>

    You should define a string conversion method in your class like so:

        def __str__(self):
            return "Point(%s,%s)"%(self.X,self.Y)
    

    This will be used when the object is printed, or otherwise needs to be converted to a string.

提交回复
热议问题