Storing Vectors

There is no built-in vector type in Python, but you can store a vector in a tuple or list of two values, or you can define a vector class. Defining a class is probably the best option because you can refer to the components by name (x or y) rather than as an index ([0] or [1]). Listing 5 -5 demonstrates how we might begin defining a vector class. I called it Vector2 because vectors are also used in 3D games and we may want to have a 3D version of the vector class called

Vector3. In addition to the constructor there is a_str_method, which turns a Vector2 object into a string when it is printed; without it, we would have to print each component individually.

Listing 5-5. Simple Vector Definition class Vector2(object):

Figure 5-1. Creating a vector

To define a vector, we can now use Vector2 objects. For instance, a call to my_vector = Vector2(10, 20) produces a Vector2 object called my_vector. We can refer to the components of the vector individually as my_vector .x and my_vector.y.

The first thing we should add to our Vector2 class is a method to create a vector from two points, because this is the most common way to create a vector (see Listing 5-6).

Listing 5-6. Vector from Points class Vector2(object):

@classmethod def from_points(cls, P1, P2):

The function from_points looks like a normal function, but the line where it is defined is preceded by @classmethod, making it a class method. These class methods are called from the class and not an instance of the class, such as Vector2.from_points(P1, P2). I made from_points a class method because it creates a new Vector2 object rather than modifying an existing one. Listing 5-7 shows how we would use it to create a vector between two points.

Listing 5-7. Testing the from_points Method

A = (10.0, 20.0) B = (30.0, 35.0) AB = Vector2.from_points(A, B) print AB

Executing this example produces the following output:

Was this article helpful?

0 0

Post a comment