• No results found

Tuples, classes, dictionaries and sets

12.1 New types

Before we continue with Pygame there are two concepts of Python you need to know: Tuples and classes. For classes you only need to know how to use them for now. But a simple example how they are defined helps understanding the principle. In chapter 1 we have seen the list type, which we use regularly in simulations to make tables. For instance like this:

import matplotlib.pyplot as plt # Create tables ttab = [] ytab = [] # Initialize y = 100.0 vy =0.0 t = 0.0 dt = 0.01 # Run simulation while y>0.: t = t + dt vy = vy –g*dt y = y + vy*dt ytab.append(y) ttab.append(t) # Plot y plt.plot(ttab,ytab) plt.show()

Here we note two things: an empty list is created and later elements are added. These elements could be changed later. We could set ytab[i] to a certain value. But what is also notable is the fact that we call the append function (or method) with the variable:

variablename.append(value)

We have seen a similar syntax with strings: varname.sort() or varname.upper(). The reason for this is that lists and strings are actually so-called classes: a sort of specific variable type with data and functions as a part of its definition.

This syntax is often seen when using modules. Since one of the powers of Python is the number of modules included and freely available on the internet, this deserves some extra attention in the final paragraph on classes.

12.2 Tuples

Lists have been discussed in chapter 2 and in the previous chapter on Numpy we have already seen a new type of lists called arrays, as used by Numpy. In fact, the list-type is the most simple and versatile form of an array- or list-type of variable. It can contain different types and each element can be treated as an independent variable. But there are many more list-like types, one is the so-called tuple.

A tuple is a list but it is immutable (just like strings). This means it cannot be changed once it is created. The variable can be overwritten by a new tuple, but individual element cannot be assigned a different value, nor can elements be added or removed. This is the only difference between lists and arrays. To distinguish between lists and tuples we use the round (normal) brackets to define a tuple. It is also possible to leave the brackets a way, this also indicates you want to create a tuple. So two valid ways to create a tuple are:

origin = (0,0) pos = 3,4

If you call a function with a tuple, you always need the round brackets, see the line with d2 below:

d1 = dist(origin,pos) d2 = dist((3,4),(-3,6))

If you would leave the brackets away in the second line, Python would think you call the function dist with four arguments.

Tuples can, just like lists, and unlike Numpy arrays, contain a mix of different types such as integers and floats etc..

It seems like a tuple is a list with a limitation, so what are they used for? Tuples can be seen as multi-dimensional values. So for instance if you want to specify an RGB-colour by its red-green- blue components you could use the following assignment to defines these colours for later calls to a graphical library: black = (0,0,0) white = (255,255,255) brightred = (255,0,0) red = (127,0,0) cyan = (0,255,255)

We’ve also already seen that maptlotlib.pyplot.legend() used a tuple for the legend text, Although this legend() function can also be called with a list. In the next chapter about Pygame, tuples are used for colors and positions.

There are many more list-like types. In most cases the list type will work for you. But sometimes a special list-like type can be convenient. If you’re curious, check the Python documentation on sets and dictionaries.

12.3 Classes and methods (object oriented programming)

In Python, next to function definitions, you can also define you own variables types and associated functions. This is what classes are. Imagine we could design a new type of variable called Pos, short for position. We want it to hold an x- and y-coordinate and we want to be able to do vector-wise addition. Also a length function will give is the length of a two-dimension position vector. Then we would be able to write a program like below:

posa = Pos(3,4) posb = Pos(-1,5)

distvector = posa.sub(posb) dist = distvector.length()

To be able to do this we need to tell Python what our type of variable, our class, is and what the functions should do. This is done by defining a new so-called class Pos:

from math import sqrt

class Pos:

def __init__(self, xcoord, ycoord):

self.x = xcoord self.y = ycoord return def sub(self,pos2): rx = self.x - pos2.x ry = self.y - pos2.y newp = Pos(rx,ry) return newp def length(self): return sqrt(self.x*self.x+self.y*self.y)

After the header a number of methods are defined. They use the same syntax as the definition of a function. So a method is a special type of function connected to the class Pos. It is therefore also called by the syntax varname.methodname(arguments).

Note that a special function __init__ is defined first: the so-called “constructor”. It is called automatically upon creation of a new instance of the class (like for posa and posb in the example). This definition of __init__ tells Python how this type can be created and what to do with the arguments that may also be given. In this case, they are simply stored as members x and y. So we note there are two variables stored in a Pos-type of variable: x and y. These are called members of the class Pos.

An example of how to use this class (we assume we have saved the above code in the file named CPos.py):

from CPos import Pos # Example of usage: a = Pos(2,3)

c = a.sub(b) print c.x,c.y print c.length()

You can build your complete program around classes. By first defining your classes including members and methods, and building classes consisting of classes on top of each other your final program could be very short. This can be done by just calling the highest level of classes like:

sim = Sim()

running = sim.start(0.,0.,0.)

while running:

sim.update(running)

This style of programming is called object-orient programming (as opposed to normal

procedural programming) and was for some time very fashionable. It still is, but you also see a return to procedural programming or a mix. A disadvantage of object oriented programming is the huge bookkeeping you have to do, a huge advantage is the reusability of your classes in different programs. For small to medium sized programs the disadvantages clearly outweigh the advantages. For most scientific computing purposes a procedural program will do fine. However, it could be useful to build your own libraries with specific computations for specific types of physics or technology. For instance a class called aircraft could contain a position, altitude, angles etc.

Object oriented programming is beyond the scope of this reader. You do not need to know how to define your own classes. You have already been using classes when calling string methods or list methods. For this course, it is only important that you know that the concept exists and why you sometime call methods or access members. It also explains this strange syntax of

variablename-period-method(arguments) like list.append(x).

It is important for you to know how to use the classes and how to call methods inside a class. Especially in Pygame we see two new types of variables used a lot: a surface and a rectangle. These are classes. One designed to hold a bitmap, the other to hold a position and a size of any rectangle. In the rectangle class not only methods are used but also members, (like top, width, height) can be assigned a value. This will be shown in examples in the Pygame chapter. Even though the concept of classes and object-oriented programming may be difficult, using modules with classes is surprisingly easy and user-friendly, as we have already seen with lists and strings and we will also see in the Pygame chapter.

12.4 Dictionaries & Sets Dictionaries

Two special types of lists can be handy. Dictionaries are list where you do no use an index but a key to look up a value.

An example of a dictionary:

>>> ages = { "Bob": 20 , "Alice": 18 ,"Jacco": 29 } >>> ages["Jacco"]

29

>>> ages["Jet"]

Traceback (most recent call last): File "<pyshell#10>", line 1 ages["Jet"]

KeyError: 'Jet' >>>

Sets

Sets are lists used for unordered collections of unique elements. It is used to check membership of a collection, overlaps of collections, etc.

It is defined similarly to a list (square brackets) with the function set. Example of the use of sets: >>> a = set([3,1,34,65,2,2,1]) >>> a set([1, 34, 3, 2, 65]) >>> if 2 in a: print 'yes' yes >>> 2 in a True >>> b = set([1,6,7,10,2,3,7])

>>> a|b # which elements are in a or b?

set([1, 34, 3, 6, 65, 10, 7, 2])

>>> a&b # which elements are in a and b?

set([1, 2, 3])