Object oriented programming (OOP) is a programming technique where both code and data are encapsulated into one single unit, known as an object. Like its meaning in a spoken language, an object can be pretty much anything you like – real world objects such as a cat a ball a customer a country, or more abstract programming objects such as – the player the game map the player’s inventory etc
As mentioned above an object is composed of both code and data. An object’s code is called a method, it’s the OOP equivalent of the function which was looked at earlier. The data it holds are called fields and both methods and data are local to the object.
OOP is quite a broad subject and we only skim the surface here, covering those parts that are relevant to the example game.
To create an object we first need to define its class, which is like a blueprint for making the object. Think of the class as a blueprint for a house, and an object as the house itself.
A cat object might have data fields for its age and weight and color, while the actions it performs such as sleeping eating purring are its methods:
class Cat: intAge = 4 intWeight = 15 strColor = "black" def printPurr(self): print ("the cat purrrrrs") def printSleep(self): print ("the cat sleeps") def printEat(self): print ("the cat eats") def printAge(self): print (self.intAge) objCat = Cat() objCat.printPurr() print ("the cat's age is %d" % objCat.intAge) objCat.intAge = 6 objCat.printAge()
The program starts with a definition of the cat Class. This is just a definition and the code inside it is not executed yet, not until it’s explicitly called in the main program. There are 3 field variables which are assigned values, followed by the definition of 4 methods. All of the methods must have at least one parameter which refers to itself, it’s usually called self but you’re free to use another name if you prefer (the interpreter passes this value to the method, you don’t send it as an argument.)
After the class definition comes the main code, which starts executing with the statement objCat = Cat (). What this does is create a cat object from the cat class blueprint, and gives it the name objCat.
On the next line we execute one of the cat object’s methods printPurr which simply displays some text on screen. As you can see this is done by typing the object’s name followed by a dot and then the method name.
Then we print the cat’s age by accessing the intAge field, again using the object’s name followed by a dot and then the field name.
After that we change the intAge field and give it the value of 6. This is then printed on screen using the printAge method. Notice how this method refers to its own object’s fields by using the self parameter.
Comic Relief
What do communists and procedural programmers have in common?
They both hate classes.