Making a Point Class in Python

前端 未结 4 1977
旧时难觅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:11

    Hum, why not use complex instead of a point class? It has all the properties you are searching for and more (such as rotation).

    Here is an example to "OOP" the complex with a pedantic notation:

    https://gist.github.com/jul/9286835

    0 讨论(0)
  • 2020-12-17 06:15

    In your Point.distance method, you reference other.X and other.Y; Other does not exists.

    You should either change the distance signature to be distance(self, other) or change the code to use p.

    You will also need to import math.sqrt:

    from math import sqrt
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-17 06:24

    Don't forget math.hypot

    def distance(self, p):
        dx = self.X - p.X
        dy = self.Y - p.Y
        return hypot(dx, dy)
    
    0 讨论(0)
提交回复
热议问题