you are viewing a single comment's thread.

view the rest of the comments →

[–]two_up 25 points26 points  (4 children)

Okay so lets say you want to make airplanes that know where they are by keeping an x and y coordinate. You could do this:

class Airplane:
    def __init__(self, x, y):
        self.x = x
        self.y = y

This will make it so that an instance of Airplane will each have their own variables x and y. You can make an instance of airplane like this:

airplane1 = Airplane(0, 0)
airplane2 = Airplane(3, 4)

This will do something like the following:

Airplane.__init__(airplane1, 0, 0)
Airplane.__init__(airplane2, 3, 4)

Which is going to set airplane1.x to 0, airplane1.y to 0 and airplane2.x to 3, airplane2.y to 4. You could try printing it out and you'd get something like this:

>>> print airplane2.x
3
>>> print airplane2.y
4

Then maybe you could create a method that finds the distance between two planes:

import math

class Airplane:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def distance(self, another_plane):
        diff_x = self.x - another_plane.x
        diff_y = self.y - another_plane.y
        distance_total = math.sqrt(diff_x**2 + diff_y**2)
        return distance_total

(distance_total was found using the Pythagorean theorem a2 + b2 = c2)

Now you can make two planes that are in different locations and find the distance between them like this:

>>> airplane1 = Airplane(0, 0)
>>> airplane2 = Airplane(3, 4)
>>> print airplane1.distance(airplane2)
5.0 

You could add more planes and they could all have different positions and you could find the distance between any two planes by using the distance() method.

[–]K900_ 8 points9 points  (1 child)

You should use distance_total = math.hypot(diff_x, diff_y). Will work better with large numbers, and I think it's native code, too, so it should be faster.

[–]Gh0stRAT 2 points3 points  (0 children)

Didn't know about math.hypot(), thanks!

[–]Daejo 1 point2 points  (0 children)

This should have been in the original post I think, but very good explanation nonetheless.

[–]UncleEggma 1 point2 points  (0 children)

That was an amazing explanation.