Hardware Reference
In-Depth Information
should start moving and stop. Without these messages, if the chicken wasn't moving, you
wouldn't know if the problem was with this module, or whether the problem was elsewhere.
Being able to see what is going on in a program is very important when debugging. Computer
scientists describe it has having good visibility . One way to achieve this is to have print
statements at key points in a program so as it executes you can follow its progress and the state
of data. It's very common for a program to not work perfectly the irst time, so designing it to make
it easy to debug can save time in the long run, particularly when you might add a new feature later.
Creating Classes
he ile chicken.py makes uses a particular style of programming called object-orientated
programming (OOP) . You don't need to worry too much if you don't understand the code at
the moment; there are more examples of OOP in other chapters in the topic.
OOP is a handy way to group code and data together. hink about any object in the real world:
It has characteristics, also called attributes, and it has things that can be done to it. For example,
a balloon's attributes include its colour and if it is inlated. Actions that can be done to it include
blowing it up or popping it. You may have a room full of diferent balloons, but they can all be
considered to share the same set of attributes and actions (even though the value of the attri-
bute, like the colour, might be diferent). As such, they are all the same class of object.
In OOP, the programmer designs his or her own classes of objects, which have a set of attri-
butes and functions. In chicken.py , the Chicken class of the object is deined by class
Chicken(): . he next indented block deines the methods (another name for functions) of
the class. here are methods to start and stop the chicken from moving and one to make it
speak. he __init__ method is a special method that is called when an object is created. In
this case, it calls the pfio initialisation method (to initialise the PiFace interface) and sets up
the object's attributes. his can be handy, as you can use your object without worrying about
what you need to do to initialise things irst. So far, the program has only created a class for
the chicken. It hasn't created an actual object, merely a description of what a Chicken object
will be like. It's a bit like creating a cookie cutter - you've deined what shape the cookies will
be, but you've not actually created any cookies yet.
Creating Objects
A Chicken object is created in the test_chicken function. It is outside the class deini-
tion (and therefore not part of the Chicken class) because it's not within the indented block.
he statement tweetyPi = Chicken(pfio,0) creates a new Chicken object called
tweetyPi . he arguments are used to pass in the PiFace Digital interface and identify which
pin the motor is connected to.
 
Search WWH ::




Custom Search